“This is the 19th day of my participation in the Gwen Challenge in November. Check out the details: The Last Gwen Challenge in 2021”

An introduction to Array objects

What it does: Uses a single variable name to store a series of values. Index: Starting from zero, the first element in the array is 0, the second element is 1, and so on.

attribute describe
constructor Returns a function that creates a prototype Array object.
length Sets or returns the number of elements in an array.
prototype Allows you to add properties and methods to arrays.

Method 1: for loop

var arr1 = [0.1];
var arr2 = [2.3];
for(var i=0; i<arr2.length; i++){
  arr1.push(arr2[i])
}
console.log(arr1); // [0, 1, 2,3]
Copy the code

Method 2: concat()

Add the parameters to the original array. This method creates a copy of the current array, appends the received arguments to the end of the copy, and returns the newly constructed array. Without passing arguments to the concat() method, it simply copies the current array and returns a copy.

var arr1 = [0.1];
var arr2 = [2.3];
var newArr = arr1.concat(arr2);
console.log(newArr); // [0, 1, 2,3]
Copy the code
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]
Copy the code

As you can see from the above test results, if you pass in an array instead of an array, you add the parameters directly to the array. If you pass in an array, you add the items from the array to the array. But what if you pass in a two-dimensional array?

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

In the above code, the fifth item of the arrCopy2 array is a two-item array, which means that the concat method can only add each item in the passed array to the array. If some of the items in the passed array are arrays, this array item is added to arrCopy2 as an item.

Apply hijacks array push (recommended)

var arr1 = [0.1];
var arr2 = [2.3];
arr1.push.apply(arr1, arr2);
console.log(arr1) // [0, 1, 2,3]
Copy the code

Method 4: Use es6 ‘dot syntax’ to extend operators (recommended)

var arr1 = [0.1];
var arr2 = [2.3]; arr1.push(... arr2);console.log(arr1) / /,1,2,3 [0]
Copy the code