Summary of JS array

Array creation

There are two ways to create arrays in JavaScript. The first is to use the Array constructor

var arr1 = new Array(); //Create an empty array
var arr2 = new Array(20); // Create an array of 20 items
var arr3 = new Array("lion","lingxi"); // Create an array of 2 strings

The second basic way to create an array is to use the literal representation of the array

var arr4 = []; //Create an empty array
var arr5 = [20]; // Create an array containing 1 item
var arr6 = ["lion","lingxi"]; // Create an array of 2 strings

When reading and setting the value of an array, use square brackets and provide a 0-based numeric index of the corresponding value:

var arr6 =  ["lion","lingxi"]; // Create an array of 2 strings
alert(arr6[0]); //lion
arr6[1] = "mary"; //Change the second item to mary
arr6[2] = "sean"; //Add the third item as sean

The length attribute of an array in JavaScript can be modified. See the following example:

var arr =["lion","lingxi"];// Create an array of 2 strings
arr[arr.length] = "sean"; //Add a "sean" at the end of the array
arr.length = arr.length-1; //Delete the last item of the array

If we need to determine whether an object is an Array object, before ECMAScript 5, we can use the instance of Array to determine, but the problem with the instance of operator is that it assumes only one global execution environment. If a web page contains multiple frames, there are actually more than two different global execution environments, so there are more than two different versions of Array constructors. If you pass an Array from one frame to another, the passed in Array and the Array originally created in the second frame have different constructors.
ECMAScript 5 adds the Array.isArray() method. The purpose of this method is to ultimately determine whether a value is an array, regardless of the global execution environment in which it was created.

Array method

Next, we will introduce the array methods. The array methods include the array prototype method and the method inherited from the object object. Here we only introduce the array prototype method. The array prototype methods mainly include the following:
push() and pop()
shift() and unshift()
indexOf() and lastIndexOf() (new in ES5)
forEach() (new in ES5)
map() (new in ES5)
filter() (new in ES5)
every() (new in ES5)
some() (new in ES5)
reduce() and reducereight() (new in ES5)


join(separator): the elements of the array are grouped into a string, with separator as the separator. If omitted, the default comma is used as the separator. This method only takes one parameter: separator.

var arr = [1,2,3];
console.log(arr.join()); // 1,2,3
console.log(arr.join("-")); // 1-2-3
console.log(arr); // [1, 2, 3] (the original array remains unchanged)

Through the join() method, you can repeat the string. You only need to pass in the string and the number of times to return the repeated string. The function is as follows:

function repeatString(str, n) {
return new Array(n + 1).join(str);
console.log(repeatString("abc", 3)); // abcabcabc
console.log(repeatString("ha", 5)); // hahahahaha

2. push() and pop()

push(): you can receive any number of parameters, add them to the end of the array one by one, and return the length of the modified array.
pop(): remove the last item at the end of the array, reduce the length value of the array, and then return the removed item.

var arr = ["lion","lingxi","Tom"];
var count = arr.push("Jack","Sean");
console.log(count); // 5
console.log(arr); // ["lion", "lingxi", "Tom", "Jack", "Sean"]
var item = arr.pop();
console.log(item); // Sean
console.log(arr); // ["lion", "lingxi", "Tom", "Jack"]

3. shift() and unshift()

shift(): delete the first item of the original array and return the value of the deleted element; undefined if the array is empty.
unshift: adds a parameter to the beginning of the original array and returns the length of the array.

This set of methods corresponds to the above push() and pop() methods. One is the beginning of the operation array, and the other is the end of the operation array.

var arr = ["lion","lingxi","Tom"];
var count = arr.unshift("Jack","Sean");
console.log(count); // 5
console.log(arr); //["Jack", "Sean", "lion", "lingxi", "Tom"]
var item = arr.shift();
console.log(item); // Jack
console.log(arr); // ["Sean", "lion", "lingxi", "Tom"]


sort(): array items are arranged in ascending order -- that is, the smallest value is at the top and the largest value is at the bottom.

When sorting, the sort () method calls the toString() transformation method of each array item, and then compares the resulting strings to determine how to sort. Even if every item in the array is a numeric value, the sort() method compares strings, so the following situation occurs:

var arr1 = ["a", "d", "c", "b"];
console.log(arr1.sort()); // ["a", "b", "c", "d"]
arr2 = [13, 24, 51, 3];
console.log(arr2.sort()); // [13, 24, 3, 51]
console.log(arr2); // [13, 24, 3, 51] (meta array changed)

To solve the above problem, the sort() method can take a comparison function as an argument so that we can specify which value precedes which one. The comparison function receives two parameters. If the first parameter should be before the second, it returns a negative number. If the two parameters are equal, it returns 0. If the first parameter should be after the second, it returns a positive number. Here is a simple comparison function:

function compare(value1, value2) {
    if (value1 < value2) {
        return -1;
    } else if (value1 > value2) {
        return 1;
    } else {
        return 0;
arr2 = [13, 24, 51, 3];
console.log(arr2.sort(compare)); // [3, 13, 24, 51]

If you need to generate descending sorting results through the comparison function, just exchange the values returned by the comparison function

function compare(value1, value2) {
    if (value1 < value2) {
        return 1;
    } else if (value1 > value2) {
        return -1;
    } else {
        return 0;
arr2 = [13, 24, 51, 3];
console.log(arr2.sort(compare)); // [51, 24, 13, 3]


reverse(): reverses the order of array items.

var arr = [13, 24, 51, 3];
console.log(arr.reverse()); //[3, 51, 24, 13]
console.log(arr); //[3, 51, 24, 13] (original array changed)


concat(): add parameters to the original array. This method first creates a copy of the current array, then adds the received parameters to the end of the copy, and finally returns the newly constructed array. Without passing parameters to the concat () method, it just copies the current array and returns a copy.

var arr = [1,3,5,7];
var arrCopy = arr.concat(9,[11,13]);
console.log(arrCopy); //[1, 3, 5, 7, 9, 11, 13]
console.log(arr); // [1, 3, 5, 7] (the original array has not been modified)

From the above test results, we can find that if the input is not an array, the parameters will be added directly after the array. If the input is an array, the items in the array will be added to the array. But what if you pass in a two-dimensional array?

var arrCopy2 = arr.concat([9,[11,13]]);
console.log(arrCopy2); //[1, 3, 5, 7, 9, Array[2]]
console.log(arrCopy2[5]); //[11, 13]

In the above code, the fifth item of arrCopy2 array is an array containing two items. That is to say, the concat method can only add each item in the incoming array to the array. If some items in the incoming array are arrays, the array item will be added to arrCopy2 as one.


Slice (): returns a new array composed of items from the specified beginning subscript to the specified ending subscript in the original array. The slice () method can take one or two parameters, that is, to return the start and end positions of an item. In the case of only one parameter, the slice() method returns all the items from the position specified by the parameter to the end of the current array. If there are two parameters, the method returns the item between the start and end positions -- but not the end position.

var arr = [1,3,5,7,9,11];
var arrCopy = arr.slice(1);
var arrCopy2 = arr.slice(1,4);
var arrCopy3 = arr.slice(1,-2);
var arrCopy4 = arr.slice(-4,-1);
console.log(arr); //[1, 3, 5, 7, 9, 11] (the original array has not changed)
console.log(arrCopy); //[3, 5, 7, 9, 11]
console.log(arrCopy2); //[3, 5, 7]
console.log(arrCopy3); //[3, 5, 7]
console.log(arrCopy4); //[5, 7, 9]

arrCopy only sets one parameter, that is, the starting subscript is 1, so the returned array starts from subscript 1 (including subscript 1) to the end of the array.
arrCopy2 sets two parameters to return the subarray of starting subscripts (including 1) and ending subscripts (excluding 4).
Two parameters are set in arrCopy3. The ending subscript is negative. When a negative number appears, the negative number is added with the value of array length (6) to replace the number at that position. Therefore, it is a subarray from 1 to 4 (not included).
The two parameters in arrCopy4 are both negative numbers, so they are converted to positive numbers by adding array length 6, which is equivalent to slice(2,5).


splice(): a powerful array method. It has many usages and can be deleted, inserted and replaced.

Delete: you can delete any number of items. You only need to specify two parameters: the position of the first item to be deleted and the number of items to be deleted. For example, splice(0,2) removes the first two items in the array.

Insert: you can insert any number of items to the specified position. You only need to provide three parameters: starting position, 0 (number of items to be deleted) and the items to be inserted. For example, splice(2,0,4,6) inserts 4 and 6 from position 2 of the current array.
Replacement: you can insert any number of items into the specified position and delete any number of items at the same time. You only need to specify three parameters: starting position, number of items to be deleted and any number of items to be inserted. The number of inserted items does not have to be equal to the number of deleted items. For example, splice (2,1,4,6) will delete the item at position 2 of the current array, and then insert 4 and 6 from position 2.

The splice() method always returns an array containing the items deleted from the original array, or an empty array if no items are deleted.

var arr = [1,3,5,7,9,11];
var arrRemoved = arr.splice(0,2);
console.log(arr); //[5, 7, 9, 11]
console.log(arrRemoved); //[1, 3]
var arrRemoved2 = arr.splice(2,0,4,6);
console.log(arr); // [5, 7, 4, 6, 9, 11]
console.log(arrRemoved2); // []
var arrRemoved3 = arr.splice(1,1,2,4);
console.log(arr); // [5, 2, 4, 4, 6, 9, 11]
console.log(arrRemoved3); //[7]

9. indexOf() and lastIndexOf()

indexOf(): takes two parameters: the item to look up and (optional) the index representing the starting point of the search. Where, look backward from the beginning of the array (position 0).
lastIndexOf: takes two parameters: the item to find and (optional) the index that represents the starting point of the find. Where, look forward from the end of the array.

Both methods return the position of the item to be found in the array, or – - 1 if not found. The congruent operator is used when comparing the first parameter with each item in the array.

var arr = [1,3,5,7,7,5,3,1];
console.log(arr.indexOf(5)); //2
console.log(arr.lastIndexOf(5)); //5
console.log(arr.indexOf(5,2)); //2
console.log(arr.lastIndexOf(5,4)); //2
console.log(arr.indexOf("5")); //-1


forEach(): loop through the array and run the given function for each item in the array. This method has no return value. The parameters are all of function type. By default, there are parameters to pass. The parameters are: traversal array content; The second is the corresponding array index, the array itself.

var arr = [1, 2, 3, 4, 5];
arr.forEach(function(x, index, a){
console.log(x + '|' + index + '|' + (a === arr));
// The output is:
// 1|0|true
// 2|1|true
// 3|2|true
// 4|3|true
// 5|4|true


map(): refers to "mapping", which runs the given function on each item in the array and returns the array composed of the results of each function call.

The following code uses the map method to square each number in the array.

var arr = [1, 2, 3, 4, 5];
var arr2 ={
return item*item;
console.log(arr2); //[1, 4, 9, 16, 25]


filter(): "filter" function. Each item in the array runs the given function and returns the array that meets the filtering conditions.

var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
var arr2 = arr.filter(function(x, index) {
return index % 3 === 0 || x >= 8;
console.log(arr2); //[1, 4, 7, 8, 9, 10]


every(): judge whether each item in the array meets the condition. Only if all items meet the condition, will true be returned.

var arr = [1, 2, 3, 4, 5];
var arr2 = arr.every(function(x) {
return x < 10;
console.log(arr2); //true
var arr3 = arr.every(function(x) {
return x < 3;
console.log(arr3); // false


some(): judge whether there are items satisfying the condition in the array. As long as one item satisfies the condition, it will return true.

var arr = [1, 2, 3, 4, 5];
var arr2 = arr.some(function(x) {
return x < 3;
console.log(arr2); //true
var arr3 = arr.some(function(x) {
return x < 1;
console.log(arr3); // false

15. reduce() and reducereight ()

Both methods iterate through all the items of the array and then build a final returned value. The reduce() method starts from the first item of the array and traverses it one by one to the end. Reducereight() starts from the last item of the array and traverses forward to the first item.

Both methods take two parameters: a function called on each term and (optional) the initial value as the basis of the merge.

The functions passed to reduce() and reducereight() take four parameters: the previous value, the current value, the index of the item, and the array object. Any value returned by this function is automatically passed to the next item as the first parameter. The first iteration occurs on the second item of the array, so the first parameter is the first item of the array, and the second parameter is the second item of the array.

The following code uses reduce() to achieve the sum of the array. The initial value of 10 is added to the array at the beginning.

var values = [1,2,3,4,5];
var sum = values.reduceRight(function(prev, cur, index, array){
return prev + cur;
console.log(sum); //25

Tags: Javascript function

Posted by AshleyByrom on Thu, 13 May 2021 05:09:29 +0930