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]
push() method can accept multiple arguments. The arguments can be Strings, Numbers, Arrays, Objects or Boolean.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With