I’m trying to push multiple elements as one array, but getting an error:
JavaScript
x
5
1
> a = []
2
[]
3
> a.push.apply(null, [1,2])
4
TypeError: Array.prototype.push called on null or undefined
5
I’m trying to do similar stuff that I’d do in ruby, I was thinking that apply
is something like *
.
JavaScript
1
5
1
>> a = []
2
=> []
3
>> a.push(*[1,2])
4
=> [1, 2]
5
Advertisement
Answer
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])
)