[ ].push.apply()和Array.prototype.push.apply()有区别吗?

下面两段代码

let arr1 = [1, 2, 3, 4, 5];
let arr2 = [6, 7, 8, 9, 10];

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

let arr1 = [1, 2, 3, 4, 5];
let arr2 = [6, 7, 8, 9, 10];

[].push.apply(arr1, arr2)

这两种写法得到的结果是相同的,它们有什么区别吗?

阅读 8.4k
4 个回答

理论上Array.prototype.push[].push要快. 因为[].push这种方式需要在原型链上查找两次才能捕获到push方法. 写个bench:

const count = 1000000
const a = [1, 2, 3]
console.time('[]')
for (let i = 0; i < count; i++) {
    [].push.apply([], a)
}
console.timeEnd('[]')
console.time('Array')
for (let i = 0; i < count; i++) {
    Array.prototype.push.apply([], a)
}
console.timeEnd('Array')

在线地址: https://jsfiddle.net/hedyegok/

事实证明是对的, Array.prototype.push要稍稍快一点点, 大概10%的样子.

[].push === Array.prototype.push,没有区别

没什么太大的不同,第二种写法本质上也是调用[].__proto__也就是Array.prototype上的push函数,除了会创建一个数组对象以外没有不同,不过浏览器对这个应该有优化,加上又少写很多字符,很多库中都是用的第二种写法。

一样的
[].push()是Arrary.prototype.push()的另外一种写法
其实最根本的东西是Arrary.prototype.push()这个方法

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题