Definition 1.#
An array is a set of values arranged in order. Each value position is numbered (starting at 0), and the entire array is represented by square brackets.
var arr = ['a'.'b'.'c'];
Copy the code
In addition to assigning at definition time, arrays can also be defined before they are assigned.
var arr = [];
arr[0] = 'a';
arr[1] = 'b';
arr[2] = 'c';
Copy the code
Any type of data can be put into an array.
var arr = [
{a: 1},1.2.3].function() {return true;}
];
arr[0] // Object {a: 1}
arr[1] / / [1, 2, 3]
arr[2] // function (){return true; }
Copy the code
If the elements of an array are still arrays, you have a multidimensional array.
var a = [[1.2], [3.4]];
a[0] [1] / / 2
a[1] [1] / / 4
Copy the code
2. The nature of arrays
Essentially, an array is a special kind of object. The Typeof operator returns an array of type Object.
typeof [1.2.3] // "object"
Copy the code
The JavaScript language dictates that the key name of an object is a string, so the key name of an array is a string. It can be read numerically because key names that are not strings are converted to strings.
var arr = ['a'.'b'.'c'];
arr['0'] // 'a'
arr[0] // 'a'
Copy the code
Note that this is also true when assigning. A value is always converted to a string and then assigned as a key name.
var a = [];
a[1.00] = 6;
a[1] / / 6
Copy the code
3. Length attribute
The length property of an array, which returns the number of members of the array.
['a'.'b'.'c'].length / / 3
Copy the code
As long as it’s an array, it must have a length property. This property is a dynamic value equal to the largest integer in the key name plus 1.
var arr = ['a'.'b']; arr.length// 2arr[2] = 'c'; arr.length // 3arr[9] = 'd'; arr.length // 10arr[1000] = 'e'; arr.length // 1001
Copy the code
The length attribute is writable. If you artificially set a value less than the current number of members, the number of members in the array is automatically reduced to the value set by length.
var arr = [ 'a'.'b'.'c']; arr.length// 3arr.length = 2; arr // ["a", "b"]
Copy the code
An effective way to empty an array is to set the length property to 0.
var arr = [ 'a'.'b'.'c']; arr.length =0; arr/ / []
Copy the code
If length is artificially greater than the current number of elements, the number of members of the array increases to this value, and the new positions are empty.
var a = ['a']; a.length = 3; a[1] // undefinedCopy the code
JavaScript will report an error if length is set to an invalid value.
[]. Length = math.pow (2, 32)// RangeError: Invalid array length = 2 ^ 32 []. Length = math.pow (2, 32)// RangeError: Invalid array length// Set string []. Length = 'ABC '// RangeError: Invalid array length
Copy the code
It’s worth noting that since an array is essentially an object, you can add attributes to an array, but that doesn’t affect the value of the Length attribute.
vara = []; a['p'] = 'abc'; a.length/ / 0 a [2.1] = 'ABC'; a.length // 0
Copy the code
If the array’s key name is to add an out-of-range value, the key name is automatically converted to a string.
vararr = []; arr[-1] = 'a'; arr[Math.pow(2.32)] = 'b'; arr.length// 0arr[-1] // "a"arr[4294967296] // "b"
Copy the code
In the code above, we added two invalid numeric keys to the array ARr, resulting in the length property unchanged. These numeric keys become string keys. The last two lines get values because the numeric key is converted to a string by default.
4. The in operator
The operator in, which checks for the presence of a key name, applies to objects as well as arrays.
var arr = [ 'a'.'b'.'c' ];2 in arr // true'2' in arr // true4 in arr // false
Copy the code
The above code shows that the array has a key named 2. Since the key names are all strings, the value 2 is automatically converted to a string.
Note that the in operator returns false if a position in the array is empty.
vararr = []; arr[100] = 'a';100 in arr // true1 in arr // false
Copy the code
5.for… In loop and array traversal
for… An in loop can iterate not only over objects but also over groups of numbers, since arrays are just a special kind of object.
var a = [1.2.3];for (var i in a) { console.log(a[i]); }/ / 1 / / 2 / / 3
Copy the code
However, for… In traverses not only all numeric keys in the array, but also non-numeric keys.
var a = [1.2.3]; a.foo =true;for (var key in a) { console.log(key); }// 0// 1// 2// foo
Copy the code
The code above also iterates over the non-integer key foo as it iterates over the number array. Therefore, it is not recommended to use for… In traverses the number group.
Consider a for loop or a while loop for array traversal.
var a = [1.2.3];// for loop for(var I = 0; i < a.length; i++) { console.log(a[i]); }// while loop var I = 0; while (i < a.length) { console.log(a[i]); i++; }var l = a.length; while (l--) { console.log(a[l]); }
Copy the code
The forEach method for arrays can also be used to iterate over arrays, as described in the Array Objects section of the Library.
var colors = ['red'.'green'.'blue']; colors.forEach(function (color) { console.log(color); });// red// green// blue
Copy the code
6. Empty space in the array
When there is an empty element somewhere in an array, that is, there is no value between two commas, the array is said to have a hole.
var a = [1.1]; a.length/ / 3
Copy the code
Note that if the last element is followed by a comma, no space is created. In other words, the result is the same with or without the comma.
The empty space of the array is readable, returning undefined.
vara = [, , ,]; a[1] // undefined
Copy the code
Using the delete command to delete an array member creates a void and does not affect the length attribute.
var a = [1.2.3];delete a[1]; a[1] // undefineda.length // 3
Copy the code
There’s a difference between an array where a position is empty and an array where a position is undefined. If it is empty, use the array’s forEach method, for… The in structure and the object. keys method are traversed, and the empty space is skipped.
vara = [, , ,]; a.forEach(function (x, i) { console.log(i + '. '+ x); })For (var I in a) {console.log(I); }// do not generate any output object.keys (a)// []
Copy the code
If a position is undefined, it will not be skipped when traversing.
var a = [undefined.undefined.undefined]; a.forEach(function (x, i) { console.log(i + '. '+ x); });// 0. undefined// 1. undefined// 2. undefinedfor (var i in a) { console.log(i);}// 0// 1// 2Object.keys(a)// ['0', '1', '2']
Copy the code
That is, a void means that the array doesn’t have that element, so it won’t be iterated over, whereas undefined means that the array has that element, so it won’t be skipped over.
7. Array-like objects
If all the keys of an object are positive integers or zero and have the length attribute, the object is much like an array and is syntactically called an array-like object.
var obj = { 0: 'a'.1: 'b'.2: 'c'.length: 3}; obj[0] // 'a'obj[1] // 'b'obj.length // 3obj.push('d') // TypeError: obj.push is not a function
Copy the code
The essential feature of “array-like objects” is the length attribute. As long as you have the Length attribute, you can think of this object as resembling an array. One problem, however, is that this length attribute is not a dynamic value and does not change as members change.
var obj = { length: 0}; obj[3] = 'd'; obj.length/ / 0
Copy the code
The above code adds a numeric key to the object obj, but the length property remains the same. So that tells us that OBj is not an array.
Typical “array-like objects” are the arguments objects for functions, as well as most DOM element sets, and strings.
Function args() {return arguments}var arrayLike = args('a', 'b'); ArrayLike [0] // 'a' arraylike.length // 2arrayLike instanceof Array // false// DOM element set var elts = document.getElementsByTagName('h3'); Elts.length // 3elts instanceof Array // false// String 'ABC '[1] // 'b'' ABC '. Length // 3' ABC' instanceof Array // false
Copy the code
The slice method of arrays turns “array-like objects” into real arrays.
var arr = Array.prototype.slice.call(arrayLike);
Copy the code
Instead of converting to a real array, another way to use array methods is to call() and place the array’s methods on the object.
function print(value, index) { console.log(index + ':'+ value); }Array.prototype.forEach.call(arrayLike, print);
Copy the code
The following example calls the forEach method on the Arguments object using this method.
/ / the forEach method function logArgs () {Array. Prototype. ForEach. Call (the arguments, the function (elem, i) { console.log(i + '. ' + elem); }); Function logArgs() {for (var I = 0; i < arguments.length; i++) { console.log(i + '. ' + arguments[i]); }}
Copy the code
A similar string Array object, so you can also use Array. Prototype. ForEach. Call traversal.
Array.prototype.forEach.call('abc'.function (chr) { console.log(chr); });// a// b// c
Copy the code
Note that this method is slower than using forEach native to arrays, so it’s best to first convert “array-like objects” to real arrays, and then call the array’s forEach method directly.
var arr = Array.prototype.slice.call('abc'); arr.forEach(function (chr) { console.log(chr); });// a// b// c
Copy the code