Arrays in JavaScript
first, the definition of the array
An array is an ordered collection of values, or an array is an ordered list of Data.
second, Create an array
" literal form "
1. empty Array
var arr=[];
2 . Array with elements
var arr=[1,2,3,1,2];
3, the array value can be any type
var arr=[1,2.3, ' foodoir ', true,null,undefined,[1,2,3],{name: ' Foodoir ', age:21}];
Attention:
1, the value of the array literal is not necessarily a constant, they can be any expression;
2, it can contain the object literal ({name: ' Foodoir ', Age:21}) and other array literals ([[+]);
3, if the array of elements or arrays, it forms a multidimensional array, such as: var arr=[[1,2,3],[4,[5,6]];
4. When using digital literal notation, The array constructor is not Called.
4 . Omit a value from the array, the default value is undefined
var arr=[1,,3]//equivalent to [1,undefined,3]
Omitting a value from the array, which causes the array to become a sparse array, it is important to note that
1, Var arr=[,,], this method under different browsers, the results of the operation is not the same
In ie8, the value of undefined is added at the end, for example var arr=[1,2,], equivalent to [1,2,undefined], when the length of the array is 3
In other browsers, the last comma, such as Var arr=[1,2, is automatically ignored, which is equivalent to [], when the length of the array is 2
2, In addition to the literal way directly constructs the sparse array, but also can be constructed by the delete operator, see the following about the delete introduction
! Import: an array that is sparse enough is usually slower to implement than a dense array (continuous array), with higher memory utilization, and the time to find elements in such an array is as long as a regular object property lookup!
" create an array by using the constructor array () "
1. no parameters when calling
var arr=new Array ()
Attention
An empty array, equivalent to arr=[];
2. pass a parameter when calling
var arr=new Array (5);
Attention
1, The representative specified the length of the array is 5, equivalent to the Var arr=[];arr.length=5;
2, if is: var arr=new array[5]; Output: undefined is not a function at this point, you should notice the symbol after the array, otherwise error-prone
3, if is: var arr=new Array (' 5 '); console.log (a[0],a.length); 5,1 Description The array created at this time has only one item, it has a length of 1 and a value of 5
If you know the number of array elements in advance, you can specify them by parameter, and this form of array () constructor can be used to allocate an array space.
3, more than two parameters
var arr=new Array (1,2.3, ' Foodoir ', null,undefined,true,false,[1,23,4]);
Attention
The display specifies the values in the array, which can be for multiple types, with var arr=[1,2.3, ' foodoir ', true,null,undefined,[1,2,3],{name: ' Foodoir ', age:21}, and similar;
Also: when using the Array () constructor, you can omit the new operator, for example: var arr=array (three-to-three);
Iii. Use of arrays
1, according to the subscript to find the corresponding value
arr[subscript]= value;
Read the value by subscript var arr = [1,2,3,4]; Console.log (arr[0]);//1, indicating that the subscript of the array starts with 0 Console.log (arr[4]),//undefined, the length of the array is 4, the value of the arr[4] is not reached//the value before the change arr[0] = ' Hello '; Console.log (arr);//hello,2,3
Note: the subscript in the array starts from 0
2. adding elements to the array
arr[subscript]= value;
Arr.push (value,...): adds an element at the end of an array
Arr.shift (value,...): array starts adding elements
Add a value to the array by subscript var arr = [1,2,3,4];arr[4] = ' World '; console.log (arr);//1,2,3,worldarr[9] = 10;console.log (arr);// 1,2,3,world,,,,, 10//can also be such var x= 2;console.log (arr[x]);//3arr[x] = 333;console.log (arr);//1,2,333,4,world,,,,, 10// Add one or more elements at the end of the array push () var arr = [];arr[0] = ' a '; arr[0] = ' A '; arr.push (' c '); arr.push (' d ', ' e ', ' F ', 123,4.5, ' Foodoir '); Console.log (arr); Console.log (arr.length);//8//adds One or more elements to the header of the array unshift () arr.unshift (n/a); console.log (arr);// 1,2,3,a,c,d,e,f,123,4.5,foodoirconsole.log (ARR.LENGTH);//11
3. reading elements in an array
arr[subscript], with 1
4 . Modifying elements in an array
Arr[subscript]= value; Same as 1
5. Delete elements in an array
Delete arr[subscript]
Note: Deleting an array element with Delete does not change the length property of the array
Arr.pop (): Delete elements of an array
Arr.unshift (): Delete the element at the beginning of the array
You can delete the elements after the array by setting the Length property
Delete an element in an array by array subscript var arr = [];console.log, ' a ', ' hello ' (arr);d elete arr[1];//delete The second element in the array console.log (arr);//1,,3, A,helloconsole.log (ARR.LENGTH);//5 The length of the array does not change//delete the element at the end of the array pops (); var arr = [1,2,3,4.5, ' foodoir '];var a = Arr.pop ();// pops up the last element Console.log (a);//foodoir, at which point the last element in the array is 4.5arr.pop ();//delete the last element console.log (arr);//the result is: 1,2,3console.log ( Arr.length);//3//deletes the header in the array var a = Arr.shift (), console.log (a);//1console.log (arr);//2,3//by Setting the length property, delete the element after the array var arr = [1,2,3,4,5,6];arr.length = 3;//sets The length of the array to 3//console.log (arr);//1,2,3arr.length = 0;//removes All data from the array console.log ( arr);//array[0]
Add: some of the data on the method of using arrays refer to the Stack method queue method, Here We also understand the previous example
Stack method:
Pop () deletes and returns the last element of the array
Push () adds one or more elements to the end of the array and returns the new Length.
Queue Method:
Shift () deletes and returns the first element of the array
Push () adds one or more elements to the end of the array and returns the new length
Unshift () adds one or more elements to the beginning of the array and returns the new Length.
1, the stack is a LIFO (last-in-first-out, Lifo) data structure, that is, the most recently added items were first Removed. The insertion (push) and removal of items in the stack occur only in one place-the top of the Stack. The ECMAScript provides the push () and pop () methods for an array that can implement a stack-like Behavior.
The push () method can receive parameters for arbitrary data, add them to the end of the array one by one, and return the modified array Length. The pop () method removes the last item from the end of the array, reducing the length value of the array
2, the stack data structure access rules are LIFO (lifo), and the queue data structure access rules are FIFO (first-in-first-out, fifo). The queue adds items at the end of the list, removing items from the front end of the List. The push () method is the method of adding an item to the end of the array, so to simulate a queue requires only a method--shift () that gets an item from the front of the array, which can move the first item in the group and return the item, as well as the length-1 of the Array. Using the shift () and push () methods together, you can use arrays as you would with Queues.
In addition, ECMAScript provides the unshift () method, which adds any item to the front of the array and returns the length of the new array. therefore, using the Unshift () and pop () methods together, You can simulate the queue in the opposite direction, that is, adding items to the front end of the array, removing items from the end of the array
Iv. iterating through an array
1,for loop traversal subscript continuous Array
2.for-in Traversal Array
3. iterating through the array through foreach ()
Syntax: Array.foreach (function (value[,index[,array]]) {functional Body})
How to traverse in an Array//when the index is contiguous, you can use the For loop to traverse var arr = [' a ', ' b ', ' c ', 123];for (var i = 0; i<arr.length;i++) {console.log (arr[i]);//a , B,c,123}//when the index is discontinuous, you can use for/in loop var arr1 = [];arr1[1] = ' x '; arr1[22] = ' y '; arr1[333] = ' Z '; for (var i in Arr1) {console.log (ar R1[i])//x,y,z}//this method iterates through inherited properties, and if you do not want to traverse inherited properties, you can use the hasOwnProperty () function for (var i in Arr1) {if (arr1.hasownproperty (I)) { Console.log (arr1[i]);//x,y,z}}//this method Iterates through the attributes that are not inherited//we can also iterate through the array through the ForEach () method/syntax: array.foreach (function (value[, index[,array]] {function body}) var arr2 = [1,2,3,4,5,6];//method one: arr2.foreach (function (x) {console.log (x);}); 1,2,3,4,5,6//method two: function Test (element,index,array) {console.log (' The array to process Is: ' +array); console.log (' index: ' +index+ '-- Values Are: ' +element);} Arr2.foreach (Test);
V. Common methods of arrays
1,array.join ([delimiter])
Describe
Concatenate the values in an array into a string
Parameters
Connect with the specified delimiter, if not specified, by default, Connect
return value
Returns the string after the connection
Attention
Array.join () is the reverse operation of the String.Split () method
Summary: Array Conversion method: join
In general, array items are returned as comma-delimited characters, and the Join method can use a different delimiter to construct the string, and the Join method takes only one argument, a string that is used as a delimiter, and then returns all strings that contain array items
2. Array.reverse ()
Describe
Array inversion
return value
Returns the array after inversion
3. Array.Sort ()
Describe
Array sort function
Parameters
If you call sort without parameters, the array is sorted alphabetically, ascending
return value
Returns the array after sorting
Attention
If the array contains undefined elements, they are queued to the end of the array, such as:
var a = [1,2,4,undefined,3,5];
Console.log (a.sort ());//0:1 1:2 2:3 3:4 4:5 5:undefined
Summary:Reverse () and sort () are the two methods that exist in the array that can be used for reordering
4,array.concat (value,...)
Describe
Creates and returns a new array that contains the elements of the original array that called Concat and each parameter of the Concat.
return value
Returns the new array after the connection
Attention
If any of these parameters itself is an array, then the elements of the array are connected, not the array itself
5,array.slice (start[,end])
Describe
Returns the part of an array
Parameters
Start Start point
End Position
return value
Returns the part of an array
6,array.splice (index, howmany[, element1[, ...) [, elementn]])
Describe
Add or remove one or more elements from an array
Parameters
Index modifies the content from which one of the arrays Begins. If the length of the array is exceeded, the content is automatically added from the end of the array, or, in the case of a negative value, the first from the bottom of the array.
Howmany is an integer that represents the number of array elements to Remove. If Howmany is 0, the element is not Removed. In this case, you should add at least one new Element. If the howmany exceeds the total number of elements after the index, all elements from index backward to the end of the array are deleted (with the index bit). If you do not specify the Howmany parameter (as in the second syntax above, which is the extended function of spidermonkey), all elements after the index position will be deleted (excluding the index Bit)
Element1 ... The element to add into the Array. If not specified, the splice only deletes the array elements.
return value
An array of elements that are Deleted. If only one element is deleted, an array containing only one element is Returned. If no element is deleted, an empty array is Returned.
Attention
If the number of elements added into an array is not equal to the number of elements being deleted, the length of the array will change accordingly.
7,array.push (value,...)
Describe
Add one or more elements like the end of an array
Parameters
The added value
return value
Returns the length of an array
8,array.pop ()
Describe
The last element of the popup array
return value
Returns the popup element
9,array.unshift (value,...)
Describe
Add one or more elements to the beginning of the array
Parameters
The added value
return value
Returns the length of an array
Ten,array.shift ()
Describe
Popup Array Start element
return value
Returns the value after the popup
Summary: these four methods are called: stack and queue method,
One,array.map ()
Describe
Returns a new array that consists of a return value from each element in the original array that invokes a specified method
Grammar
Array.map (callback)
Parameters
Callback callback function
The first parameter of the currentvalue,callback, the element that is currently passed in the array
The second parameter of the index,callback, the index of the element that is currently passed in the array
The third argument of array,callback, which calls the array of the map method
Attention
The map method invokes the callback function sequentially for each element in the original array
Callback the return value of each execution is combined to form a new array.
The callback function is called only on indexed indexes that have never been assigned a value or deleted using Delete.
array.filter ()
Describe
Method tests all elements with the specified function and creates a new array that contains all the elements passed by the test
Grammar
Arr.filter (callback)
Attention
The filter invokes the callback function once for each element in the array and creates a new array with all elements that make callback return TRUE or value equivalent to True
Callback are only called on indexes that have already been assigned, and are not called for indexes that have been deleted or have never been assigned a Value. Elements that are not tested by callback are skipped and are not included in the new Array.
, array.reduce ()
Describe
The reduce method receives a function as an accumulator, and each value (from left to Right) in the array begins to shrink, resulting in a value
Grammar
Arr.reduce (callback,[initialvalue])
Parameters
Callback
previousvalue, the value returned by the last call or the provided initial value (initialvalue)
currentvalue, the element currently being processed in the array
index, the current element is indexed in the array
array, calling the arrays of reduce
initialvalue, as the first argument to call callback for the first time
Attention
Reduce each element in the array executes the callback function in turn, excluding the element that has been deleted or never assigned to it, and accepts four parameters: the initial value (or the return value of the last callback function), the current element value, the current index, and the array that called reduce
When the callback function executes for the first time, Previousvalue and CurrentValue can be a value, and if InitialValue is provided when you call reduce, the first previousvalue equals initialvalue, and cur Rentvalue equals the first value in the array, and if InitialValue is not supplied, then Previousvalue equals the first value in the array, and CurrentValue equals the second value in the Array.
, array.reduceright ()
Describe
The opposite of the reduce () method execution direction
, array.some ()
Describe
Tests whether certain elements in the array pass the test of the specified function
Grammar
Arr.some (callback)
Attention
Some executes the callback function once for each element in the array until it finds a value that causes callback to return a truth (which can be converted to a Boolean value of True)
, array.every ()
Describe
Tests whether all elements of the array have passed the test of the specified Function.
Grammar
Arr.every (callback)
Attention
The Every method executes the callback function once for each element in the array until it finds an element that causes callback to return falsy, which represents a value that can be converted to a Boolean value of False. If one of these elements is found, the Every method returns False immediately. otherwise, callback returns True for each element returned true,every. Callback are only called for those indexes that have already been assigned Values. are not called for indexes that have been deleted or have never been assigned a value
, Array.indexof ()
, Array.lastindexof ()
, Array.isarray ()
Describe
Detects whether a value is an array
20, array.tostring ()
Describe
Returns a String that represents the specified array and its elements.
return value
Returns a String that represents the specified array and its elements.
Attention:
1, The return value of the method is consistent with the method of calling join without any parameters, such as [1,2,3].tostring ();/'
2. Because alert receives a string argument, it calls the ToString () method in the background and gets the same result as the ToString () method, such as alert ([//1,2,3]);
21, array.tolocalestring ()
toLocaleString () is a localized version of the ToString () method, and he often returns the same results as the ToString () method
If an item in the array has a value of NULL or undefined, the result returned in the toLocaleString () and ToString () methods is represented by an empty string, such as:
var a=[1,null,2,undefined,3];
Console.log (a.tolocalestring ());//1,,2,,3
Console.log (a.tostring ());//1,,2,,3
The difference between the two can be understood by the following example:
The toLocaleString method returns a String object that contains the date represented by the default format of the current Locale.
For the time between A.D. 1601 and 1999, the date format is determined by the regional settings in the User's control panel.
F for other times outside of this interval, use the default format of the toString Method.
For example, also March 21, in the United states, toLocaleString may return "03/21/08 01:02:03", while in Europe the return value may be "21/03/08 01:02:03" because it is customary in Europe to put the date in front of the Month.
toLocaleString is only used to display the results to the user, preferably not in the script to do basic calculations, because the results returned are different from the MACHINE.
22,Array. ValueOf ()
The ValueOf () method returns the array object itself
var a=[1,2,3];
Console.log (a.valueof ());//[1,2,3]
Console.log (a.valueof () instanceof Array);//true
Summary: tostring,tolocalestring and ValueOf methods are inherited methods that belong to the object!
They are used in the following ways:
The commonly used methods in arrays are var arr = [' a ', ' b ', ' C ', ' d ', ' e '];//joinvar a = arr.join ();//a,b,c,d,e default = "," A = arr.join (",");//a,b,c,d,ea = AR R.join ("");//ABCDE modified to null Console.log (a),//reverse reversal a = Arr.reverse (); console.log (a);//sort () sort var arr1 = [' a ', ' b ', ' C ', ' A ', ' B ', ' C '];var A = arr1.sort (); console.log (a);//a,b,c,a,b,c The default sort is sort by code//you can also specify the order of the sort in var arr2 = [ 1,2,3,11,15,20,23,30];var a = Arr2.sort (); console.log (a);//1,11,15,2,20,23,3,30var a = Arr2.sort (function (a, b) { Return a-b;}); Console.log (a);//1,2,3,11,15,20,23,30var a = arr2.sort (function (a, b) {return b-a;}); Console.log (a);//30,23,20,15,11,3,2,1var users = [{name: ' foodoir ', age:21},{name: ' Hello ', age:33},{name: ' World ', Age : 44},{name: ' Jake ', age:55},];//console.log (users), users.sort (function (b) {if (a.name>b.name) return 1;if ( A.name<b.name) Return-1;return 0;}); /console.log (users); (var i in Users) {console.log (users[i][' name ')}//note is the access to the array inside the Name property method is users[i][' name ']}// Concat the link of the array var arr = [1,2,3];var A = Arr.concat (' a ');//1,2,3,avar a = Arr.concat ([4, 5,6]) var a = Arr.concat ([4,[5,[' a ', ' b ', ' c ']]); console.log (a);//slice () var arr = [' a ', ' b ', ' C ', ' d ', ' e ', ' F ', ' G ', ' H ', ' i ' ];var a = Arr.slice (0,3); console.log (a);//a,b,cvar a = Arr.slice (0,-2); console.log (a);//a,b,c,d,e,f,gvar a = Arr.slice ( -5,-3);//console.log (a);//e,fvar a = Arr.slice ( -5,3);//not present console.log (a);//e,fvar a = Arr.slice ( -5,0);// There is no console.log (a);//e,fvar a = Arr.slice (4);//represents the beginning of the fifth from the left, until the end of the array console.log (a);//e,f,g,h,ivar a = Arr.slice (-4);// Represents the beginning of the fourth from the right, until the end of the array console.log (a);//f,g,h,iconsole.log (arr);//the original array does not change//splicevar arr = [' a ', ' b ', ' C ', ' d ', ' e ', ' F ', ' G ', ' H ', ' i '];console.log (arr.length);//9var a = Arr.splice (0,1); console.log (a);//aconsole.log (arr);//b,c,d,e,f,g,h , Iconsole.log (arr.length);//8//this method takes the values in the array out, causing the array length to be reduced by var a = Arr.splice (5); console.log (a);//g,h,iconsole.log (arr );//b,c,d,e,fconsole.log (arr.length);//5var a = Arr.splice (0,2, '! ', '? ', '% '); console.log (a);//b,c intercepts the value b,c and the base of B,c !,?,%,console.log (arr),//!,?,%,d,e,fconsole.log (arr.length);//6//mapvar arr = [1,2,3,4,5];var a = Arr.map (function (x) {return x*x;}); Console.log (a);//1,4,9,16,25var arr = [' a! ', ' b! ', ' C ', ' d ', ' e! ']; var a = Arr.map (demo), function demo (x) {return x.replace (/!/g, '? '). toUpperCase ();//will! Switch , change lowercase to uppercase}console.log (a),//filter filter var arr = [1,2,4,8,16,32,22];var A = arr.filter (function (x) {return x<=10;}); Console.log (a);//1,2,4,8 only outputs a value less than 10 var arr1 = [1,2,4,8,16,32,21,true,false,null,undefined];var A1 = Arr1.filter ( function (x) {//filter out odd return x%2 = = 0;}); Console.log (a1);//0:2 1:4 2:8 3:16 4:32 5:false 6:null length:7var arr1 = [1,2,4,8,16,32,21,true,false,null,undefined];v AR a1 = arr1.filter (function (x) {//filter out null/undefinedreturn x!== null && x!==undefined;}); Console.log (a1);//1,2,4,8,16,32,21,true,false//reducevar arr = [1,2,3,4,5];var a = arr.reduce (function (a, b) {return A + b;}); Console.log (a);//15var a = arr.reduce (function (a, b) {return a+b;},10);//incoming initial value 10console.log (a);//25//every and Somevar Age = [11,22,33,44,55];//every, Returns True if all values in the array satisfy the condition, otherwise falsevar a = Arr.every (function (x) {return x>=18;}); Console.log (a);//false//if You change the age of 11 to 18, then true//some, returns truevar B = Arr.some (function (y) {return y< When the value in the array satisfies the Condition) 18;}); Console.log (b);//true//indexof,a first appears in the position var arr = [' a ', ' b ', ' C ', ' d ', ' e '];var res = arr.indexof (a); console.log (res);// If not, the return is -1var res = Arr.indexof (' a '); console.log (res);//if there is, return the value corresponding to the index in the array var arr = [' a ', ' b ', ' C ', ' d ', ' e ', ' a ', ' BC ', ' A '];var res = Arr.indexof (' a ', 2);//indicates from the second starting index Console.log (res),//5//lastindexof (), The last occurrence of the position var res = Arr.lastindexof (' A '); console.log (res);//array.isarray () var arr = [' a ', ' b ', ' C ', ' d ', ' e '];console.log (arr));// Trueconsole.log (array.isarray ([]));//trueconsole.log (array.isarray ({}));//false, Empty object is not an array,//array is an object, but the object is not an array// Tostringvar arr = [' a ', ' b ', ' C ', ' d ', ' e '];console.log (arr.tostring ());//a,b,c,d,econsole.log (arr.join ());//a,b,c,d, E
A detailed array in JavaScript