This article mainly introduces the Array of JavaScript, this article describes in detail the creation, detection, conversion, stack, queue, re-sorting, operation, and location methods of JavaScript arrays, for more information, see the differences between ECMAScript arrays and arrays in other languages. Although the array in ECMAScript is also an ordered list, each of its Arrays can save any type of data. The size of the ECMAScript array can be dynamically adjusted.
There are two basic methods to create an array. The first method is to use Array to construct a function, as shown below:
The Code is as follows:
Var colors = new Array ();
If you know the number of items to be saved in the array, you can also pass a parameter to the constructor, which will automatically become the value of the length attribute, as shown below:
The Code is as follows:
Var colors = new Array (20 );
You can also pass the items in the Array to the Array constructor, as shown in the following code:
The Code is as follows:
Var colors = new Array ("red", "blue ");
In addition, the new operator can be omitted when Array constructor is used, as shown below:
The Code is as follows:
Var colors = Array (20 );
The second way to create an array is to use the array literal representation. The array literal is represented by a pair of square brackets containing array items. Multiple array items are separated by commas, as shown below:
The Code is as follows:
Var color = ["red", "blue"];
Var names = [];
Var values = [1, 2,] // IE8 and the preceding three items. The other two items are not recommended.
Like an object, Array constructor is not called when numeric literal notation is used.
When reading and setting the array value, square brackets should be used and a 0-based numeric index should be provided for the corresponding value, as shown below:
The Code is as follows:
Var colors = ["red", "blue"]; // defines an array
Alert (colors [0]); // red
Colors [1] = "black" // Modify item 2nd
Colors [2] = "brown" // Add 3rd
The number of items in the array is stored in its length attribute. This attribute always returns 0 or a larger number, as shown below:
The Code is as follows:
Var colors = ["red", "blue"]; // defines an array
Var names = [];
Alert (colors. length); // 3
Alert (names. length) // 0
It is worth noting that the length value of the array is not read-only. Therefore, by setting this value, you can remove an item from the end of the array or add an item to the array, as shown below:
The Code is as follows:
Var colors = ["red", "blue"];
Colors. length = 1;
Alert (colors [1]); // undefined
The length attribute can also be used to conveniently add data to the end of the array:
The Code is as follows:
Var colors = ["red", "blue"];
Colors [colors. length] = "black"; // added in location 2
Colors [colors. length] = "brown"; // added in location 3
1. detection array
For a webpage or a global scope, you can use the instanceof operator:
The Code is as follows:
If (value instanceof Array ){
// Perform the operation
}
The limitations of the instanceof operator lies in the global scope. If a webpage contains multiple frameworks, more than two global execution environments exist. To solve this problem, ECMAScript5 adds the Array. isArray () method, using the following:
The Code is as follows:
If (Array. isArray (value )){
// Perform the operation
}
2. Conversion Method
The toString () method of the array is called to return a comma-separated string consisting of each value in the array. The returned value of () is an array. As follows:
The Code is as follows:
Var colors = ['red', 'blue', 'green'];
Alert (colors. toString (); // red, blue, green
Alert (colors. valueOf (); // red, blue, green
Alert (colors) // red, blue, green
The toLocalString (), tiString (), and valueOf () methods inherited by the array are returned by default in the form of a string with a comma separator. If you use the join () method, you can use different separators to construct this string. The join () method only accepts one parameter, that is, the string used as the separator, as shown below:
The Code is as follows:
Var colors = ['red', 'blue', 'green'];
Alert (colors. join (','); // red, blue, green
Alert (colors. join ('|'); // red | blue | green
If a value in the array is null or undefied, The results returned by the join (), toLocalString (), tiString (), and valueOf () methods are expressed as null strings.
3. Stack Method
Javascript provides push () and pop () operations for arrays to implement behavior similar to stacks.
The push () method can receive any number of parameters, add them one by one to the end of the array, and return the length of the modified array. The pop () method overflows the last item from the end of the array, reduces the length value of the array, and then returns the removed item.
The Code is as follows:
Var colors = new Array (); // defines an Array
Var count = colors. push ("red", "blue"); // press two items
Alert (count); // 2
Count = colors. push ("black"); // press another item
Alert (count); // 3
Var item = colors. pop (); // The last item is displayed.
Alert (item); // "black"
Alert (colors. length); // 2
4. Queue Method
The access rule of the stack data structure is LIFO (first-in-first-out), and the queue access rule is FIFO (first-in-first-out ). The queue adds items at the end of the list and removes items at the front end.
The shift () method can remove the first entry from the array and return the value, length-1 of the array. Combined with the push () and shift () methods, you can use arrays like using queues, as shown below:
The Code is as follows:
Var colors = new Array ();
Var count = colors. push ("red", "blue ");
Count = colors. push ("black ");
Alert (count );
Var item = colors. shift (); // obtain the first item
Alert (item); // "red"
Alert (color. length); // 2
ECMAScript also provides the unshift () method for arrays. The unshift () and shift () methods are used in the opposite way: It adds any item to the front of the array and returns the length of the new array. Therefore, the unshift () and shift () methods can be used to simulate a queue in the opposite direction, that is, add a new item at the front end of the array and remove the item from the end of the array, as shown below:
The Code is as follows:
Var colors = new Array ();
Var count = colors. push ("red", "green ");
Alert (count); // 2
Count = colors. unshift ("black"); // push to another item
Alert (count); // 3
Var item = colors. pop (); // get the last item
Alert (item) // green
Alert (colors. length) // 2
5. Re-sorting method
There are already two methods in the array that can be directly used for re-sorting: reverse () and sort (). The reverse () method sorts the reverse array items.
The Code is as follows:
Var values = [2, 1, 3, 4, 5];
Values. reverse ();
Alert (values); // 5, 4, 3, 2, 1
By default, the sort () method sorts array items in ascending order, calls the toString () method for each item, compares strings, and determines how to sort them. Even if each item in the array is a value, the sort () method compares strings.
The Code is as follows:
Var values = [12, 11, 3, 4, 5];
Values. sort ();
Alert (values); // 12, 11, 3, 4, 5
We can pass a comparison function as a parameter to the sort () method. As follows:
The Code is as follows:
Function compare (value1, value2 ){
If (value1 <value2 ){
Return-1
} Else if (value1> value2 ){
Return 1
} Else {
Return 0
}
}
Var values = [0, 1, 5, 10, 15];
Values. sort (compare );
Alert (values); // 0, 1, 5, 10, 15
6. Operation Method
ECMAScript provides many methods for operations in arrays. The concat () method can create a new array based on all the items in the current array.
The Code is as follows:
Var colors = ["red", "green", "blue"];
Var colors2 = colors. concat ("yellow", ["black", "brown"]);
Alert (colors); // red, green, blue
Alert (colors2); // red, green, blue, yellow, black, brown
Slice () method, which can create a new array based on one or more items of the current array. It can receive one or two parameters, that is, the start and end positions of the items to be returned. When a parameter is specified, all items starting at the specified position to the end of the current array are returned. Two Parameters return all the items from the start to the specified position, excluding the items at the end position. Note that the slipe () method does not affect the original array.
The Code is as follows:
Var colors = ["red", "green", "blue", "black", "brown"];
Var colors2 = colors. slice (1 );
Var colors3 = colors. slice (1, 4 );
Alert (colors2); // green, blue, black, brown
Alert (colors3); // green, blue, black
Delete slice (): You can delete any number of items. You only need to specify two parameters: the location of the first item to be deleted and the number of items to be deleted.
Insert slice () method: you can insert any number of items to a specified position. You only need to provide three parameters: Start position, 0 (number of items to be deleted), and the items to be inserted.
Slipe () method replacement: you can insert any number of items at the specified position and delete any number of items at the same time. You only need to specify three parameters: start position, number of items to be deleted, and any number of items to be inserted.
The Code is as follows:
Var colors = ["red", "green", "blue"];
// Delete
Var removed = colors. slice (0, 1); // Delete 1st items
Var colors3 = colors. slice (1, 4 );
Alert (colors); // green, blue
Alert (removed); // red
// Insert
Removed = colors. slice (1, 0, "yellow", "orange"); // insert from position 1
Alert (colors); // green, yellow, orange, blue
Alert (removed); // empty array
// Replace
Removed = colors. slice (1, 1, "red", "purple"); // insert from position 1
Alert (colors); // green, "red", "purple", orange, blue
Alert (removed); // "yellow"
7. Location Method
ECMAScript5 provides two location methods for Arrays: indexOf () and lastIndexOf (). Both methods receive two parameters: the item to be searched and the index representing the start position (optional ). Here, the indexOf () method is searched successively from the beginning of the array, and the lastIndexOf () method is searched forward from the end of the array.
Both methods return the position of the item to be searched in the array and-1 if not found.
The Code is as follows:
Var numbers = [1, 2, 3, 4, 5, 4, 3, 2, 1];
Alert (numbers. indexOf (4) // 3
Alert (numbers. lastIndexOf (4) // 5
Alert (numbers. indexOf (4, 4) // 5
Alert (numbers. lastIndexOf (4, 4) // 3
8. Iteration Method
ECMAScript5 defines five Iteration Methods for arrays. Each method accepts two parameters. The first is the iteration function, and the second is the scope object of the function. (optional ].
The function of iteration takes three parameters. The first parameter is the value of the element to be iterated in the array, and the second parameter is the position of the element that always needs to be iterated in the array, the third is iteration array itself.
1. every () runs the given function for each item in the array. If this function returns true for each item, true is returned.
2. filter () is used to run a given function for each item in the array, and returns an array composed of items that return true.
3. forEach () is used to run the given function for each item in the array. This method has no return value. 4. map () runs the given function for each item in the array and returns an array composed of the results of each function call.
5. some () runs the given function for each item in the array. If this function returns true for any item, true is returned.
Browsers supported by these iteration methods include IE9 +, Firefox2 +, Safari3 +, Opera 9.5 +, and chrome
Among these methods, the most similar are every () and some (), which are used to query whether the items in the array meet a certain condition. For every (), the input function must return true for each item to return true; otherwise, false is returned. The some () method returns true as long as the input function returns true for one of the arrays.
The Code is as follows:
Var num = [1, 2, 3, 4, 5, 6, 7, 8, 9];
Var everyResult = num. every (function (item, index, array ){
If (item> 2 ){
Return true;
}
});
Alert (everyResult); // false
Var someResult = num. some (function (item ){
If (item> 2 ){
Return true;
}
});
Alert (someResult); // true
Filter () is to use the specified function to determine whether to include a certain item in the returned array.
The Code is as follows:
Var num = [1, 2, 3, 4, 5, 4, 3, 2, 1];
Var filterResult = num. filter (function (item ){
If (item> 2 ){
Return true;
}
});
Alert (filterResult); // [3, 4, 5, 4, 3]
Map () also returns an array, and each item of this array is the result of running the input function on the corresponding item in the original array.
The Code is as follows:
Var num = [1, 2, 3, 4, 5, 4, 3, 2, 1];
Var mapResult = num. map (function (item ){
If (item> 2 ){
Return true;
}
}); // [2, 3, 6, 8, 10, 8, 6, 4, 2]
ForEach () is the input function for each item in the array. This method does not return values, essentially the same as using the for loop to iterate arrays.
The Code is as follows:
Var num = [1, 2, 3, 4, 5, 4, 3, 2, 1];
Num. forEach (function (item ){
// Perform the operation
});
9. Merge Method
ECMAScript5 adds two methods: reduceRight () and reduce (). Both methods accept two parameters: the first is the function used to iterate the array. This function has four parameters: the previous value, the current value, the index of the item, and the array object. However, any value of this function will be automatically passed to the next item as the first parameter. The second parameter is the initial value of the first parameter in the first function.
The Code is as follows:
Var nums = [1, 2, 4, 5];
Var sum = nums. reduce (function (prev, cur, index, array ){
Return prev + cur;
});
Alert (sum); // 15