push multiple elements to array

05/13/2020 13:00:01

I'm trying to push multiple elements as one array, but getting error

> a = []
[]
> a.push.apply(null, [1,2])
TypeError: Array.prototype.push called on null or undefined

I'm trying to do similar stuff that I'd do in ruby, I was thinking that apply is something like *.

>> a = []
=> []
>> a.push(*[1,2])
=> [1, 2]

Verified Answer (232 Votes)

02/06/2013 12:41:14

When using most functions of objects with apply or call, the context parameter MUST be the object you are working on.

In this case, you need a.push.apply(a, [1,2]) (or more correctly Array.prototype.push.apply(a, [1,2]))

232

Answer #2 (598 Votes)

02/06/2013 12:40:20

You can push multiple elements into an array in the following way

var a = [];
    
a.push(1, 2, 3);

console.log(a);

598

Answer #3 (422 Votes)

02/03/2016 07:57:03

Now in ECMAScript2015 (a.k.a. ES6), you can use the spread operator to append multiple items at once:

var arr = [1];
var newItems = [2, 3];
arr.push(...newItems);
console.log(arr);

See Kangax's ES6 compatibility table to see what browsers are compatible

422
3
Hack Hex uses Stack Exchance API by the Stack Exchange Inc. to scrape questions/answers under Creative Commons license.