You can push multiple elements into an array in the following way
var a = [];
a.push(1, 2, 3);
console.log(a);
Answer from amit1310 on Stack OverflowYou 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
Videos
Hey, so maybe this is a silly question but I was wondering how to measure the performance of push method, would it be preferable to push a few elements into an array at once or just push it a couple of times? I'm using console.time method to measure the diff between these two approaches, maybe there is a better/more reliable way to test this?
Example:
// one call to push method
arr.push({a:'a', b: 'b'}, {c:'c', d: 'd'});
// n calls to push method
arr.push({a:'a', b: 'b'});
arr.push({c:'c', d: 'd'});
It's just to see which one is faster more than the obvious thing to do (just push it all in one call)