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

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

apply的作用在这里有两个:

1、将操作对象换成对象a

2、将b作为push()函数的参数

这句话的意思就是:将b追加到a里面,如果a为数组,也可以写成a.push(...b)

其实这两种写法都是调用push方法而已

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]

这样写法等价的原因是因为在实例上寻找属性的时候,现在这个实例自己身上找,如果找不到,就根据内部指针__proto__随着原型链往上找,直到找到这个属性。

在这里就是寻找push方法,两种写法最后找到的都是Array构造函数对应的prototype的原生方法push。所以说两种写法是等价的。

但是为什么要使用a.push.apply(a,b);这种写法呢?为什么不直接使用push()?

如果直接push:

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

a.push(b);

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

这个apply 有一个功能和扩展运算符一样 , 就是可以把数组进行扩展,之后进行操作

// 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]

这样就看出来区别了,原生push方法接受的参数是一个参数列表,它不会自动把数组扩展成参数列表,使用apply的写法可以将数组型参数扩展成参数列表

猜你喜欢

转载自blog.csdn.net/m0_55960697/article/details/124064828