为什么 Array.push.apply 不起作用? [英] Why doesn't Array.push.apply work?
问题描述
如此处所述,在javascript中将数组b附加到数组a的一种快速方法是a.push.apply(a, b)
.
As described here, a quick way to append array b to array a in javascript is a.push.apply(a, b)
.
您会注意到对象 a 被使用了两次.实际上我们只想要 push
函数,而 b.push.apply(a, b)
完成了完全相同的事情——apply 的第一个参数提供了 用于应用的函数.
You'll note that the object a is used twice. Really we just want the push
function, and b.push.apply(a, b)
accomplishes exactly the same thing -- the first argument of apply supplies the this
for the applied function.
我认为直接使用 Array 对象的方法可能更有意义:Array.push.apply(a, b)
.但这不起作用!
I thought it might make more sense to directly use the methods of the Array object: Array.push.apply(a, b)
. But this doesn't work!
我很好奇为什么不这样做,以及是否有更好的方法来实现我的目标.(应用 push
函数而无需调用特定数组两次.)
I'm curious why not, and if there's a better way to accomplish my goal. (Applying the push
function without needing to invoke a specific array twice.)
推荐答案
It's Array.prototype.push
,不是 Array.push
这篇关于为什么 Array.push.apply 不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!