Push multiple elements to array
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 = [1];
var newItems = [2, 3];
arr.push(...newItems);
console.log(arr);
See Kangax's ES6 compatibility table to see what browsers are compatible
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])
)
You can use Array.concat
:
var result = a.concat(b);