简体   繁体   English

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

[英]Why doesn't Array.push.apply work?

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. 您会注意到对象a被使用了两次。 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. 我们真的只想要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) . 我认为直接使用Array对象的方法可能更有意义: Array.push.apply(a, b) But this doesn't work! 但这不起作用!

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.) (应用push函数而无需两次调用特定数组。)

它是Array.prototype.push ,而不是Array.push

您也可以使用[].push.apply(a, b)来缩短表示法。

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM