Reputation: 2607
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
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
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