The previous words
An array is a set of values arranged in order, and relative to the object's property names are out of order. Essentially, arrays use numbers as lookup keys, while objects have user-defined attribute names. JavaScript does not have real associative arrays, but objects can be used to implement the function of associative
Array() is just a special type of Object(), that is, an Array() instance is basically an Object() instance with some extra functionality. Arrays can hold any type of values, which can be updated or deleted at any time, and the size of the array is dynamically adjusted.
In addition to objects, array Array type is probably the most commonly used type in JavaScript. Moreover, arrays in javascript are quite different from those in most other languages. This article will introduce the array Array type in javascript
Create an array
There are two ways to create an array: using literal syntax and using Array() constructor
【Literal】
Using array literals is the easiest way to create an array. Separate array elements with commas in square brackets
var empty = []; //Array without elements var primes = [2,3,5,7,11]; //Array with 5 values
Although javascript arrays are ordered lists of data as well as arrays in other languages, unlike other languages, each item of javascript arrays can hold any type of data
var misc = [1.1,true, "a"]; //3 elements of different types
The values in array literals do not have to be constants, they can be any expression
var base = 1024;var table = [base,base+1,base+2,base+3];
It can contain object literals or other array literals
var b = [ [1,{x:1,y:2}],[2,{x:3,y:4}] ];If the elements of the array are still arrays, a multi-dimensional array is formed
var a = [[1, 2], [3, 4]];
[Note] When using numeric literal notation, the Array constructor will not be called
【Constructor】
There are three ways to call constructors
【1】No parameters, create an empty array
//This method creates an empty array without any elements, which is equivalent to the direct quantity of the array []var a = new Array();
【2】There is a numerical parameter, which is used to specify the length of the array
var a = new Array(10);console.log(a);//[]console.log(a[0],a.length);//undefined 10
[Note] If there is another type of parameter, an array containing only ones of that value will be created
var a = new Array('10');console.log(a);//['10']console.log(a[0],a.length);//10 1【3】When there are multiple parameters, the parameters are represented as specific elements of the array
var a = new Array(1,2,3);console.log(a);//[1,2,3]console.log(a[0],a[1],a[2]);//1 2 3
When using the Array() constructor, the new operator can be omitted
var a1 = Array();var a2 = Array(10);var a3 = Array(1,2,3);console.log(a1,a2,a3);//[] [] [1,2,3]
Array nature
Arrays are a set of values arranged in order. In essence, arrays are special objects.
typeof [1, 2, 3] // "object"
The particularity of an array is reflected in that its key names are a set of integers (0, 1, 2…) arranged in order. Since the key names of array members are fixed, the array does not need to specify a key name for each element, but each member of the object must specify a key name.
var arr = ['a', 'b', 'c'];console.log(Object.keys(arr));// ["0", "1", "2"]var obj = {name1: 'a',name2: 'b',name3: 'c'};Arrays are special forms of objects. Accessing array elements with square brackets is like accessing objects' properties with square brackets.
The JavaScript language stipulates that the key names of objects are strings, so the key names of arrays are actually strings. The reason why it can be read with numeric values is that non-string key names will be converted into strings and then used as attribute names
o={}; //Create an ordinary object o[1]="one"; //Index it with an integer//The numeric key name is automatically converted into a string var arr = ['a', 'b', 'c'];arr['0'] // 'a'arr[0] // 'a'However, it is necessary to distinguish between array index and object attribute names: all indexes are attribute names, but only integer attribute names between 0~232-2 (4294967294) are indexes
var a = [];//Index a['1000'] = 'abc';a[1000] // 'abc'//Index a[1.00] = 6;a[1] // 6
[Note] Individual values cannot be used as identifiers. Therefore, array members can only be expressed in square brackets
var arr = [1, 2, 3];arr[0];//1arr.0;//SyntaxError
An array can be indexed using negative or non-integer numbers. However, since it is not within the range of 0~2 to the power of 32 -2, it is only the attribute name of the array, not the index of the array. The obvious feature is that it does not change the length of the array
var a = [1,2,3];//Attribute name a[-1.23]=true;console.log(a.length);//3//Index a[10] = 5;console.log(a.length);//11//Attribute name a['abc']='testing';console.log(a.length);//11
Sparse arrays
A sparse array is an array containing discontinuous indexes starting from 0.
【1】The most direct way to make sparse arrays is to use the delete operator
var a = [1,2,3,4,5];delete a[1];console.log(a[1]);//undefinedconsole.log(1 in a);//false
【2】Element values can be omitted between commas of arrays, and sparse arrays can be created by omitting element values.
var a =[1,,3,4,5];console.log(a[1]);//undefinedconsole.log(1 in a);//false
[Note] There is a difference between the omitted element value and the element value whose value is undefined.
var a =[1,,3,4,5];console.log(a[1]);//undefinedconsole.log(1 in a);//falsevar a =[1,undefined,3,4,5];console.log(a[1]);//undefinedconsole.log(1 in a);//true
If you use commas at the end of the array, there are differences between browsers. The comma is ignored by the standard browser, while the IE8-browser adds an undefined value at the end
//Standard browser output [1,2], while IE8-browser output [1,2,undefined]var a = [1,2,];console.log(a);//Standard browser output 2, while IE8-browser output 3var a = [,,];console.log(a.length);
Arrays that are sparse enough are usually slower in implementation than dense arrays and have higher memory utilization, and the time to look up elements in such an array is as long as the time to look up properties of regular object
Array length
Each array has a length attribute, which is this attribute that distinguishes it from conventional JavaScript objects. For dense (that is, non-sparse) arrays, the length attribute value represents the number of elements in the array, and its value is 1 larger than the largest index in the array.
[].length //=>0: The array has no elements ['a','b','c'].length //=>3: The maximum index is 2, and the length is 3
When an array is a sparse array, the length attribute value is greater than the number of elements. Similarly, its value is 1 larger than the largest index in the array
[,,].length; //3(Array(10)).length;//10var a = [1,2,3];console.log(a.length);//3delete a[1];console.log(a.length);//3
The particularity of arrays is mainly reflected in the fact that the length of the array can be adjusted dynamically:
【1】If you assign a value to an array element and index i is greater than or equal to the length of the existing array, the value of the length attribute will be set to i+1
var arr = ['a', 'b'];arr.length // 2arr[2] = 'c';arr.length // 3arr[9] = 'd';arr.length // 10arr[1000] = 'e';arr.length // 1001
【2】When setting the length attribute to a non-negative integer n smaller than the current length, elements with the current array index value greater than or equal to n will be deleted from it
a=[1,2,3,4,5]; //From the array of 5 elements a.length = 3; //Now a is [1,2,3]a.length = 0; //Delete all elements. a is []a.length = 5; //The length is 5, but there are no elements, just like new
Array(5)
[Note] An effective way to clear the array is to set the length property to 0
var arr = [ 'a', 'b', 'c' ];arr.length = 0;arr // []
【3】Set the length attribute value of the array to be greater than its current length. Actually this does not add new elements to the array, it just creates an empty area at the end of the array
var a = ['a'];a.length = 3;console.log(a[1]);//undefinedconsole.log(1 in a);//false
If length is set to an illegal value (i.e., a value outside the range 0--232-2), javascript will report an error
// Set negative value[].length = -1// RangeError: Invalid array length// The number of array elements is greater than or equal to 2 to the power of 32[].length = Math.pow(2,32)// RangeError: Invalid array length// Set string[].length = 'abc'// RangeError: Invalid array length
Since an array is essentially an object, you can add attributes to the array, but this does not affect the value of the length attribute
var a = [];a['p'] = 'abc';console.log(a.length);// 0a[2.1] = 'abc';console.log(a.length);// 0
Array traversal
The most common way to loop through array elements using for loop
var a = [1, 2, 3];for(var i = 0; i < a.length; i++) {console.log(a[i]);}Of course, you can also use a while loop
var a = [1, 2, 3];var i = 0;while (i < a.length) {console.log(a[i]);i++;}var l = a.length;while (l--) {console.log(a[l]);}But if the array is a sparse array, use a for loop and you need to add some conditions
//Skip non-existent element var a = [1,,,2];for(var i = 0; i < a.length; i++){if(!(i in a)) continue;console.log(a[i]);}You can also use for/in loops to process sparse arrays. The loop assigns an enumerable attribute name (including array index) to the loop variable at a time. The non-existent index will not be traversed to
var a = [1,,,2];for(var i in a){console.log(a[i]);}Because the for/in loop can enumerate inherited attribute names, such as methods added to Array.prototype. For this reason, for/in loops should not be used on arrays unless additional detection methods are used to filter unwanted properties
var a = [1,,,2];ab = 'b';for(var i in a){console.log(a[i]);//1 2 'b'} //Skip ivar a = [1,,,2];ab = 'b';for(var i in a){if(String(Math.floor(Math.abs(Number(i)))) !== i) continue;console.log(a[i]);//1 2}The JavaScript specification allows for for/in loops to traverse the properties of an object in different orders. Usually, the traversal implementation of array elements is in ascending order, but it cannot be guaranteed to be like this. In particular, if an array has both object attributes and array elements, the returned attribute names are likely in the order they were created rather than in the order of the numerical size. If the algorithm depends on the order of traversal, it is best not to use for/in but to use regular for loops
Class array
Objects with length attributes and corresponding non-negative integer attributes are called array-like objects
//Class array demonstration var a = {};var i = 0;while(i < 10){a[i] = i*i;i++;}a.length = i;var total = 0;for(var j = 0; j < a.length; j++){total += a[j];}There are three common class array objects:
【1】arguments object
// arguments object function args() { return arguments }var arrayLike = args('a', 'b');arrayLike[0] // 'a'arrayLike.length // 2arrayLike instance of Array // false【2】Object returned by DOM method (such as document.getElementsByTagName() method)
// DOM element var elts = document.getElementsByTagName('h3');elts.length // 3elts instanceof Array // false【3】String
// String 'abc'[1] // 'b''abc'.length // 3'abc' instance of Array // false
[Note] Strings are immutable values, so when viewed as arrays, they are read-only. For example, push(), sort(), reverse(), splice() and other array methods will modify the array. They are invalid on the string and will report an error
var str = 'abc';Array.prototype.forEach.call(str, function(chr) {console.log(chr);//abc});Array.prototype.splice.call(str,1);console.log(str);//TypeError: Cannot delete property '2' of [object String]The slice method of an array turns the class array object into a real array
var arr = Array.prototype.slice.call(arrayLike);
JavaScript array methods are specifically defined as general, so they work correctly not only on real arrays but also on class array objects. In ECMAScript5, all array methods are general. In ECMAScript3, all methods except toString() and toLocaleString() are also common
var a = {'0':'a','1':'b','2':'c',length:3};Array.prototype.join.call(a,'+');//'a+b+c'Array.prototype.slice.call(a,0);//['a','b','c']Array.prototype.map.call(a,function(x){return x.toUpperCase();});//['A','B','C']