Arrays

JavaScript Arrays (JavaScript数组)

In this chapter, we will explore JavaScript arrays. (在本章中,我们将探讨JavaScript数组。)

In JavaScript, you can use arrays for storing multiple values in a single variable. (在JavaScript中,可以使用数组在单个变量中存储多个值。)

We can describe an array as a unique variable capable of holding more than one value simultaneously. (我们可以将数组描述为能够同时保存多个值的唯一变量。)

There exist two syntaxes for generating an empty array:

let arr = new Array();
let arr = [];

The second syntax is used most of the time. You can add initial elements in the brackets, like this:

let books = ["Html", "Css", "Javascript"];
console.log(books[0]); // Html
console.log(books[1]); // Css
console.log(books[2]); // Javascript

You can also replace an element as follows:

let books = ["Html", "Css", "Javascript"];
books[2] = 'Php'; // now ["Html", "Css", "Php"]
console.log(books);

Either you can add a new one to the array, like this:

let books = ["Html", "Css", "Javascript"];
books[3] = 'Php'; // now ["Html", "Css", "Javascript", "Php"]
console.log(books); // Html, Css, Javascript, Php

The array length is the total count of the elements. Here is an example:

let books = ["Html", "Css", "Javascript"];
console.log(books.length); // 3

In case you are going to show the overall array, you may use console.log, like this:

An array is capable of storing any types of elements:

// mix of values
let arr = ['Javascript', { sitename: 'w3cdoc'}, true, function () {
 console.log('welcome');
}];
// get the object at index 1 and then show its name
console.log(arr[1].sitename); // w3cdoc
// get the function at index 3 and run it
arr[3](); // welcome

Arrays can be viewed as a special type of object. One of the most notable similarities is that arrays can end with a comma. (数组可以被视为一种特殊类型的对象。最显着的相似之处之一是数组可以以逗号结尾。)

For instance:

let books = [
"Html",
("0")
"Css",
(CSS)
"Javascript",
];

Methods

Methods (方法)

One of the most widespread uses of arrays is a queue. in computer science, it is known as an ordered assembly of elements that support the following two operations:

push - is used for appending an element to the end (push -用于将元素附加到末尾)

shift - is used for getting an element from the beginning, advancing the queue. In consequence, the second element becomes the first. (shift -用于从头开始获取元素,推进队列。因此,第二个元素成为第一个元素。)

Arrays support both of the above-mentioned operations, and it’s a widespread practice for developers. (数组支持上述两种操作,这对开发人员来说是一种普遍的做法。)

You can use arrays for another practice as well. It’s data structure named stack, which supports two operations:

push - it’s aimed at adding an element to the end. (push -它的目的是在末尾添加一个元素。)

pop - is aimed at taking an element from the end. (pop -旨在从末尾获取元素。)

In javascript, arrays work with as a queue and as a stack. With the help of arrays, you can add or remove elements to/from the beginning or the end.

Methods working with the end of an array

Methods working with the end of an array (使用数组结尾的方法)

pop (啪)

This method is used for extracting and returning the last element of the array. For instance:

let books = ["Html", "Css", "Javascript"];
console.log(books.pop()); // remove "Jasvascript" and alert it
console.log(books); // Html, Css

push

You can use this method for appending the element to the end of the array, like this:

let books = ["Html", "Css"];
books.push("Javascript");
console.log(books); // Html, Css,  Javascript

The calls books.push(…) and books[books.length] = … are equal. (调用books.push (…)和books [books.length] =…是相等的。)

Methods working with the beginning of the array

Methods working with the beginning of the array (使用数组开头的方法)

shift (v.移动 ,转移 ;n.转移)

This method is targeted at extracting and returning the first element of the array. (此方法旨在提取并返回数组的第一个元素。)

For example:

let books = ["Html", "Css", "Javascript"];
console.log(books.shift()); // remove Html and show it
console.log(books); // Css, Javascript

unshift

This one is used to add the element to the beginning of the array, as follows:

let books = ["Css", "Javascript"];
books.unshift('Html');
console.log(books); // Html, Css, Javascript

With the help of methods push and unshift, you can simultaneously add different elements. (借助push和unshift方法,您可以同时添加不同的元素。)

Let’s have a look at this example:

let books = ["Html"];
books.push("Css", "Javascript");
books.unshift("Php", "C#"); // ["Php", "C#", "Html", "Css", "Javascript"]
console.log(books);

Internals

Internals (内部)

As we mentioned above, arrays are a special type of object. Square brackets can be used to access a property arr[0] come from the syntax of the object. One thing makes an array even more special. It’s their internal representation. The engine tends to store its elements consecutively in the contiguous memory area. But, note that they will break if you quit to work with the array in the given order and deal it as an ordinary object. (如上所述,数组是一种特殊类型的对象。 方括号可用于访问来自对象语法的属性arr [0]。 有一件事让数组变得更加特别。 这是他们的内部表现。 引擎倾向于将其元素连续存储在连续的内存区域中。 但是,请注意,如果您退出按给定顺序处理数组并将其作为普通对象处理,它们将中断。)

For example, it is technically possible to act like this:

let books = []; // make an array 
books[99999] = 5; // assign a property with the index far greater than its length 
books.name = "Javascript"; // create a property with an arbitrary name

It is available because arrays are objects. You have the option of adding properties to them. (它是可用的,因为数组是对象。您可以选择向它们添加属性。)

You should also know the cases of the array misuse to avoid them. Here are several examples:

  • Adding a non-numeric property, such as arr.test = 9. (-添加非数字属性,例如arr.test = 9。)

  • Making holes, like add arr[0] and then arr[500] putting nothing between them. (-制作孔,例如添加arr [0] ,然后在它们之间添加arr [500]。)

  • Filling the array in the reverse order. For example, arr[500], arr[499]. (-以相反的顺序填充阵列。例如, arr [500]、arr [499]。)

We can assume that one should treat arrays as unique structures working with them with the ordered data. (我们可以假设应该将数组视为处理有序数据的唯一结构。)

Loops

Loops (循环)

One of the common ways of cycling array items is the for loop over indexes. (循环数组项的常见方法之一是for循环索引。)

Here is an example:

let arr = ["Html", "Css", "Javascript"];
for (let i = 0; i < arr.length; i++) {
 console.log(arr[i]);
}

Another form of loop is for..of. (另一种形式的循环是for.. of。)

The example looks like this:

let books = ["Html", "Css", "Javascript"];
// iterates over array elements
for (let book of books) {
 console.log(book);
}

This form of the loop doesn’t give access to the number of the current element. (这种形式的循环不允许访问当前元素的编号。)

As arrays are objects, also you can technically use for..in:

let booksArray = ["Html", "Css", "Javascript"];
for (let key in booksArray) {
 console.log(booksArray[key]); // Html, Css, Javascript
}

Anyway, it’s not a good idea, as it can cause potential problems, such as:

  • The loop for..in may iterate over all the properties, not only the numeric properties. (-.. in的循环可能遍历所有属性,而不仅仅是数值属性。)

  • The loop for..in is optimized for generic objects but not arrays. That’s why it’s up to 10-100 times slower. (-.. in的循环针对泛型对象而不是数组进行了优化。这就是为什么它速度慢10-100倍的原因。)

The Length

The Length (长度)

Whenever we modify the array, the length property automatically updates. It’s not the count of values in the array, but the numeric index + 1. For example, a single element with a large index will give a great length, like this:

let books = [];
books[100] = "Html";
console.log(books.length); // 101

Anyway, developers don’t use arrays in that way. (无论如何,开发人员不会以这种方式使用数组。)

The length property is writable. When you decrease it, the array will be truncated. Let’s have a look at this example:

let arr = [1, 2, 3, 4, 5]; 
arr.length = 3; // truncate to 3 elements
console.log(arr); // [1, 2, 3] 
arr.length = 5; // return length back
console.log(arr[4]); // undefined: the values do not return

You can easily clear the array by using arr.length = 0;.

Creating a New Array

Creating a New Array (创建新阵列)

Here is another syntax for creating an array:

let arr = new Array("Html", "Css", "etc");

Anyway, this syntax is not used frequently. (无论如何,这种语法不经常使用。)

In case a new Array is called with just one argument, that is a number. After that, it creates an array without items, but with a particular length:

let arr = new Array(3); // will it create an array of [3]
console.log(arr[0]); // undefined! no elements. 
console.log(arr.length); // length 3

In the code mentioned above, all elements are undefined . (在上面提到的代码中,所有元素都是未定义的。)

Multidimensional Arrays

Multidimensional Arrays (多维数组)

Arrays might have items that are arrays, as well. It can be used for multidimensional arrays to store matrices:

let matrix = [
 [1, 2, 3],
(一 二三)
 [4, 5, 6],
(4, 5, 6.)
 [7, 8, 9]
];
console.log(matrix[1][1]); // 5, the central elementarrays

toString method

toString method (toString方法)

Arrays implement the toString method in their own way. It returns a comma-separated list of elements. Here is an example:

let arr = [1, 2, 3];
console.log(arr); // 1,2,3
console.log(String(arr) === '1,2,3'); // true

There is an alternative one, as well:

console.log([] + 1); // "1"
console.log([1] + 1); // "11"
console.log([2, 1] + 2); // "2,12"

But they don’t have Symbol.toPrimitive and valueOf. Arrays implement merely the toString conversion. Thus, here [] transforms into “1” and [2,1] becomes “2,1”.

If the binary plus “+” operator adds something to a string, it switches it to a string so that the next step looks as follows:

console.log("" + 1); // "1"
console.log("2" + 1); // "21"
console.log("2,2" + 1); // "2,21"


请遵守《互联网环境法规》文明发言,欢迎讨论问题
扫码反馈

扫一扫,反馈当前页面

咨询反馈
扫码关注
返回顶部