Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Push multiple elements to array

Tags:

javascript

I'm trying to push multiple elements as one array, but getting an 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] 
like image 458
evfwcqcg Avatar asked Feb 06 '13 07:02

evfwcqcg


People also ask

Can push take multiple arguments?

push() method can accept multiple arguments. The arguments can be Strings, Numbers, Arrays, Objects or Boolean.

How do you push an element to an array?

JavaScript Array push()The push() method adds new items to the end of an array. The push() method changes the length of the array. The push() method returns the new length.


2 Answers

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

var a = [];        a.push(1, 2, 3);    console.log(a);
like image 94
amit1310 Avatar answered Sep 20 '22 09:09

amit1310


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

like image 26
canac Avatar answered Sep 19 '22 09:09

canac