【JavaScript】- ;[].push.apply(a, b)和 Array.prototype.push.apply(a, b);

;[].push.apply(a, b) 和 Array.prototype.push.apply(a, b);

There are two roles for apply here:

1. Replace the operation object with object a

2. Use b as the parameter of the push() function

The meaning of this sentence is: append b to a. If a is an array, it can also be written as a.push(...b)

In fact, these two ways of writing are just calling the push method.

let a = [1,2,3]
let b = [4,5,6]

;[].push.apply(a, b);    // 注意:[]前面一定要有 ;分号,不然会和上一行的代码搞混在一起

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

其实这样的写法等价于:
let a = [1,2,3]
let b = [4,5,6]

Array.prototype.push.apply(a, b);

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

The reason why this way of writing is equivalent is that when looking for a property on an instance, now the instance itself is looking for it. If it cannot be found, it will search up the prototype chain according to the internal pointer __proto__ until it finds the property.

Here is to look for the push method. The two writing methods finally find the native method push of the prototype corresponding to the Array constructor. So the two ways of writing are equivalent.

But why use a.push.apply(a,b); this way of writing? Why not just use push() directly?

If you push directly:

let a = [1,2,3];
let b = [4,5,6];

a.push(b);

console.log(a)     // [1, 2, 3, Array(3)]

This apply has the same function as the spread operator, that is, the array can be expanded and then operated

// ES5 的写法
var arr1 = [0, 1, 2];
var arr2 = [3, 4, 5];
Array.prototype.push.apply(arr1, arr2);

// ES6 的写法
let arr1 = [0, 1, 2];
let arr2 = [3, 4, 5];
arr1.push(...arr2);		
console.log(arr1)	// [0,1,2,3,4,5]

This shows the difference. The parameter accepted by the native push method is a parameter list. It does not automatically expand the array into a parameter list. Using the writing method of apply can expand the array parameter into a parameter list.

 

Guess you like

Origin blog.csdn.net/m0_55960697/article/details/124064828