Using arr.push vs arr.push.apply(arr, element)



我主要使用它:

arr.push(element)

但是我看到有人这样使用:

arr.push.apply(arr, element)

这两种方法之间有什么不同?

我认为使用"列表"时更常见。使用应用时,您可以将数组分解为单个参数。

例如:

arr.push(0,1,2,3)

就像这样做一样,但是初始值在数组中:

arr.push.apply(this, [0,1,2,3])

这是一个运行示例:

var original = [1,2,3];
var arr = [];
arr.push(0);
arr.push.apply(arr, original); // pushes all the elements onto the array
console.log(arr); // 0,1,2,3

但是,在ES6中,您甚至不需要使用apply

let original = [1,2,3];
let arr = [];
arr.push(0, ...original);
console.log(arr); // 0,1,2,3

最新更新