Use apply's pass-by format to achieve array merging

Everyone should know the usage of apply, [method.apply(this points to the object, the array of values)]

fun.apply(this, [val1, val2])

One of the characteristics of apply is its second value, which is an array containing the incoming value. Using this feature of apply, it can be used for array merging

Its principle is to execute the Array.prototype.push method in the this environment of arr1, the parameter is the data released by the array arr2,
so this method will change the first array

var arr1 = [1, 2, 3];
var arr2 = [4, 5, 6];

Array.prototype.push.apply(arr1, arr2);

console.log(arr1);
// [1, 2, 3, 4, 5, 6]

console.log(arr2);
// [4, 5, 6]

Attachment:
using arr1.concat(arr2) for conventional merged arrays,
concat will return a new array without changing the two original arrays

end

Guess you like

Origin blog.csdn.net/u013970232/article/details/110359843