Previous words
In addition to objects, the array type of arrays may be the most common type in JavaScript. Also, arrays in JavaScript are quite different from arrays in most other languages. This article describes the array type of arrays in JavaScript
Create an array
There are two ways to create an array: using literal syntax and using the array () constructor
"Literal"
Using array literals is the simplest way to create an array, separating the elements of the array with commas in square brackets
var empty = []; An array with no elements var primes = [2,3,5,7,11]; Array with 5 values
Although JavaScript arrays and arrays in other languages are an ordered list of data, unlike other languages, each item of a JavaScript array can hold any type of data
var misc = [1.1,true, "a"]; 3 different types of elements
The values in the array literals are not necessarily constants, they can be arbitrary expressions
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 an array are still arrays, a multidimensional array is formed
var a = [[1, 2], [3, 4]];
[note] When using numeric literal notation, the array constructor is not called
"Constructors"
There are three ways to call constructors
"1" Without parameters, create an empty array
The method creates an empty array without any elements, equivalent to the array direct amount []var a = new Array ();
"2" has a numeric parameter that specifies the length of the array
var a = new Array, Console.log (a);//[]console.log (a[0],a.length);//undefined 10
[note] If there is a parameter of another type, an array of only one item that contains that value is created
var a = new Array (' ten '); Console.log (a);//[']console.log (a[0],a.length);//10 1
When "3" has more than one parameter, the parameter represents the specific element for the array
var a = new Array (2); Console.log (a);//[1,2,3]console.log (a[0],a[1],a[2]);//1 3
You can omit the new operator when using the array () constructor
var = array (), var a2 = array (A1), var a3 = array (n/a), Console.log (A1,A2,A3);//[] [[]
Array Nature
An array is a set of values in order, in essence, an array is a special object
typeof [1, 2, 3]//"Object"
The special body of an array now, its key name is a set of integers in order (0,1,2 ...). Because the key names of the array members are fixed, the array does not have to specify a key name for each element, and each member of the object must specify the 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, and using square brackets to access an array element is like using square brackets to access an object's properties
The JavaScript language specifies that the key name of an object is a string, so the key name of the array is actually a string. A numeric value can be read because a non-string key name is converted to a string and then used as the property name.
o={}; Create an Ordinary object o[1]= "one"; Index it with an integer//numeric key name is automatically converted to string var arr = [' A ', ' B ', ' C '];arr[' 0 ']//' a ' arr[0]//' a '
However, be sure to differentiate between the array index and the object's property name: All indexes are property names, but only integer property names between 0~232-2 (4294967294) are indexed
var a = [];//index a[' + '] = ' abc '; a[1000]//' ABC '//index a[1.00] = 6;a[1]//6
[note] Individual values cannot be used as identifiers (identifier). Therefore, array members can only be represented by square brackets
var arr = [1, 2, 3];arr[0];//1arr.0;//syntaxerror
You can use a negative or non-integer to index an array. But because it is not in the range of 0~2 32-2, it is only the property name of the array, not the index of the array, the obvious feature is not to change the length of the array
var a = [1,2,3];//property name A[-1.23]=true;console.log (a.length);//3//index a[10] = 5;console.log (a.length);//11//property name a[' abc ']= ' Testing '; Console.log (a.length);//11
Sparse array
A sparse array is an array that contains a discontinuous index starting at 0
The most straightforward way to make a sparse array of "1" is to use the delete operator
var a = [1,2,3,4,5];d elete a[1];console.log (a[1]);//undefinedconsole.log (1 in a);//false
You can omit element values between commas in the "2" array, and you can create sparse arrays by omitting the element values
var a =[1,,3,4,5];console.log (a[1]);//undefinedconsole.log (1 in a);//false
[note] There is a difference between an omitted element value and an element value of 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 is a difference between the browsers. The standard browser ignores the comma, and the ie8-browser adds the undefined value at the end
Standard browser output [ie8-], while the browser output is [1,2,undefined]var a = [1,2,];console.log (a);//Standard browser Output 2, and ie8-browser output 3var a = [,];console.log (A.length);
Sparse arrays are typically slower to implement than dense arrays, and memory utilization is higher, and the time to find elements in such an array is as long as a regular object property lookup time
Array length
Each array has a length property, which is the attribute that distinguishes it from regular JavaScript objects. For dense (i.e., non-sparse) arrays, the value of the Length property represents the number of elements in the array, which is 1 larger than the largest index in the array
[].length //=>0: The array has no elements [' A ', ' B ', ' C '].length //=>3: The largest index is 2,length for 3
When an array is a sparse array, the Length property value is greater than the number of elements, and as such, its value is 1 larger than the largest index in the array
[,,,].length; 3 (Array). Length;//10var a = [1,2,3];console.log (a.length);//3delete A[1];console.log (a.length);//3
The specificity of the array is mainly reflected in the length of the array can be dynamically adjusted:
"1" If an array element is assigned a value, index i is greater than or equal to the length of the existing array, the value of the length property is 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 the length property is less than the current length of a nonnegative integer n, the element with the current array index value greater than or equal to n is removed from the
a=[1,2,3,4,5]; Starting from an array of 5 elements a.length = 3; Now a for [1,2,3]a.length = 0; Delete all the elements. A For []a.length = 5; The length is 5, but there is no element, just like the new Array (5)
[note] An efficient way to empty an array is to set the length property to 0
var arr = [' A ', ' B ', ' c '];arr.length = 0;arr//[]
"3" Sets the value of the array's length property to be greater than its current length. This does not actually add a new element to the array, it simply 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 you set the length to an illegal value (that is, a value other than the 0--232-2 range), JavaScript will error
Set negative value [].length = -1//rangeerror:invalid array length//array elements greater than or equal to 2 32 times [].length = Math.pow (2,32)//Rangeerror:invali D array length//set string [].length = ' abc '//rangeerror:invalid array length
Because an array is essentially an object, you can add attributes to the arrays, but this does not affect the value of the length property
var a = [];a[' p '] = ' abc '; Console.log (a.length);//0a[2.1] = ' abc '; Console.log (a.length);//0
Array traversal
Using a For loop to iterate over an array element is the most common method
var a = [1, 2, 3];for (var i = 0; i < a.length; i++) { console.log (a[i]);}
Of course, you can also use the 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]);}
However, if the array is a sparse array, you need to add some conditions when using a for loop
Skipping elements that do not exist 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 the for/in loop to process sparse arrays. Each time the loop assigns an enumerable property name (including an array index) to the loop variable. Indexes that do not exist will not traverse to the
var a = [1,,, 2];for (var i in a) { console.log (a[i]);}
Because the for/in loop is capable of enumerating inherited property 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];a.b = ' B '; for (var i in a) { console.log (a[i]);//1 2 ' B '}
Skip Ivar A = [1,,, 2];a.b = ' B '; for (var i-in a) { if (String (Math.floor (Math.Abs (number (i)))!==) continue;
console.log (A[i]);//1 2}
The JavaScript specification allows for/in loops to traverse the properties of an object in a different order. Typically, the traversal implementation of an array element is ascending, but there is no guarantee that it must be. In particular, if arrays have both object properties and array elements, the returned property names are likely to be in the order in which they were created rather than the size of the numeric values. If the algorithm relies on the order of traversal, it is best not to use for/in for the regular for loop
Class Array
Objects with the Length property and corresponding nonnegative integer attributes are called class arrays (Array-like object)
The class array demonstrates var a = {};var i = 0;while (i <) { 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//2a Rraylike instanceof Array//False
The object returned by the "2" Dom method (such as the 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 ' instanceof Array//False
[note] strings are immutable values, so when they are treated as arrays, they are read-only. Array methods such as push (), sort (), reverse (), splice () will modify the array, they are invalid on the string, and will error
var str = ' abc '; Array.prototype.forEach.call (str, function (CHR) { console.log (CHR);//a b c}); Array.prototype.splice.call (str,1); Console.log (str);//typeerror:cannot Delete Property ' 2 ' of [object String]
The slice method of the array turns the class array object into a true array
var arr = Array.prototype.slice.call (arraylike);
JavaScript array methods are deliberately defined as generic, so they are not only applied to real arrays but also work correctly on class array objects. In ECMAScript5, all array methods are generic. 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 ']
Array random order
Array of disorderly order in English for Shuffle, also known as shuffle. Generally, as in the next two ways
1. A function is passed to the array's native sort () method, which randomly returns 1 or-1 for the purpose of randomly arranging array elements
var array = [1,2,3,4,5];console.log (Array.Sort () (function () {return math.random ()-0.5});//[2,1,5,4,3]
If you disrupt an array of 100,000 elements, you need about 100ms
var arr = [];var num = 100000;for (var i = 0; i < NUM; i++) { arr.push (i);} var startTime = +new date (), Arr.sort (function () {return math.random ()-0.5}); Console.log (+new date ()-startTime);//100
2. The second method is to iterate through each element in the array, iterating over the elements to exchange values with the elements of a random position
var arr = [1,2,3,4,5];for (var i = 0; i < arr.length; i++) { var randomindex = Math.floor (Math.random () *arr.length); [Arr[i],arr[randomindex]] = [arr[randomindex],arr[i]];} Console.log (arr);//[2, 3, 1, 4, 5]
If you disrupt an array of 100,000 elements, you need about 13MS, so the second method is more efficient
var arr = [];var num = 100000;for (var i = 0; i < NUM; i++) { arr.push (i);} var startTime = +new Date (); for (var i = 0; i < arr.length; i++) { var randomindex = Math.floor (Math.random () *arr.le Ngth); [Arr[i],arr[randomindex]] = [arr[randomindex],arr[i]];} Console.log (+new Date ()-startTime);//13
Resources
"1" Es5/array object https://www.w3.org/html/ig/zh/wiki/ES5/builtins#Array_.E5.AF.B9.E8.B1.A1
"2" Ruan one peak JavaScript standard reference Tutorial-basic syntax http://javascript.ruanyifeng.com/grammar/array.html
"3" JavaScript Definitive Guide (6th edition), chapter 7th, array
"4" JavaScript Advanced Programming (3rd Edition), chapter 5th reference type
"5" JavaScript DOM Programming Art (2nd Edition), chapter 2nd JavaScript syntax
6 "javascript Statement essence" Chapter 6th array
JavaScript type System