push multiple elements to array
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 = 
=> [1, 2]
When using most functions of objects with
context parameter MUST be the object you are working on.
In this case, you need
a.push.apply(a, [1,2]) (or more correctly
You can push multiple elements into an array in the following way
var a = ; a.push(1, 2, 3); console.log(a);
Now in ECMAScript2015 (a.k.a. ES6), you can use the spread operator to append multiple items at once:
var arr = ; var newItems = [2, 3]; arr.push(...newItems); console.log(arr);
See Kangax’s ES6 compatibility table to see what browsers are compatible
You can use
var result = a.concat(b);
If you want an alternative to
Array.concat in ECMAScript 2015 (a.k.a. ES6, ES2015) that, like it, does not modify the array but returns a new array you can use the spread operator like so:
var arr = ; var newItems = [2, 3]; var newerItems = [4, 5]; var newArr = [...arr, ...newItems, ...newerItems]; console.log(newArr);
Note this is different than the
push method as the
push method mutates/modifies the array.
If you want to see if certain ES2015 features work in your browser check Kangax’s compatibility table.
You can also use Babel or a similar transpiler if you do not want to wait for browser support and want to use ES2015 in production.
There are many answers recommend to use:
Array.prototype.push(a, b). It’s nice way, BUT if you will have really big b, you will have stack overflow error (because of too many args). Be careful here.
See What is the most efficient way to concatenate N arrays? for more details.