starwed
starwed

Reputation: 2607

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

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

Upvotes: 52

Views: 71452

Answers (4)

David Griffin
David Griffin

Reputation: 190

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

Upvotes: 10

erdem
erdem

Reputation: 195

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

Upvotes: 10

Ven
Ven

Reputation: 19039

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

Upvotes: 72

phenomnomnominal
phenomnomnominal

Reputation: 5515

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

Upvotes: 4

Related Questions