Why doesn't Array.push.apply work?

2019-03-22 11:06发布

问题:

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

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.

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!

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.)

回答1:

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



回答2:

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



回答3:

What is wrong with 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];


回答4:

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

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