javascript 为什么 Array.push.apply 不起作用?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15444242/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 00:47:04  来源:igfitidea点击:

Why doesn't Array.push.apply work?

javascriptarraysapply

提问by starwed

As described here, a quick way to append array b to array a in javascript is a.push.apply(a, b).

如所描述的在这里,一个快速的方法来追加数组b到阵列的在JavaScript是a.push.apply(a, b)

You'll note that the object a is used twice. Really we just want the pushfunction, and b.push.apply(a, b)accomplishes exactly the same thing -- the first argument of apply supplies the thisfor the applied function.

您会注意到对象 a 被使用了两次。实际上我们只想要这个push函数,并b.push.apply(a, b)完成完全相同的事情——apply 的第一个参数this为应用函数提供了。

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!

我想这可能更有意义,直接使用数组对象的方法:Array.push.apply(a, b)。但这不起作用!

I'm curious why not, and if there's a better way to accomplish my goal. (Applying the pushfunction without needing to invoke a specific array twice.)

我很好奇为什么不这样做,以及是否有更好的方法来实现我的目标。(应用该push函数而无需两次调用特定数组。)

回答by Ven

It's Array.prototype.push, not Array.push

Array.prototype.push,不是Array.push

回答by erdem

You can also use [].push.apply(a, b)for shorter notation.

您也可以使用[].push.apply(a, b)更短的符号。

回答by David Griffin

The current version of JS allows you to unpack an array into the arguments.

当前版本的 JS 允许您将数组解包到参数中。

var a = [1, 2, 3, 4, 5,];
var b = [6, 7, 8, 9];

a.push(...b); //[1, 2, 3, 4, 5, 6, 7, 8, 9];

回答by phenomnomnominal

What is wrong with Array.prototype.concat?

有什么问题Array.prototype.concat

var a = [1, 2, 3, 4, 5];
var b = [6, 7, 8, 9];

a = a.concat(b); // [1, 2, 3, 4, 5, 6, 7, 8, 9];