Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't Array.push.apply work?

As described here, a quick way to append array b to array a in javascript is a.push.apply(a, b).

You'll note that the object a is used twice. Really we just want the push function, and b.push.apply(a, b) accomplishes exactly the same thing -- the first argument of apply supplies the this for the applied function.

I thought it might make more sense to directly use the methods of the Array object: Array.push.apply(a, b). But this doesn't work!

I'm curious why not, and if there's a better way to accomplish my goal. (Applying the push function without needing to invoke a specific array twice.)

like image 696
starwed Avatar asked Mar 16 '13 00:03

starwed


People also ask

Can you push into an array?

push() The push() method adds one or more elements to the end of an array and returns the new length of the array.

What is array push apply?

Using apply to append an array to another Because push() accepts a variable number of arguments, you can also push multiple elements at once. But if you pass an array to push() , it will actually add that array as a single element, instead of adding the elements individually, ending up with an array inside an array.

What happens when you push an array into an array?

The array push() a built-in JavaScript function that adds a new element at the end of an array and returns the new length. The push() method modifies the length of the Array or collection, and it can append a number, string, object, Array, or any value to the array.

Does array push overwrite?

You overwrite the members in your loop. If you create a new object inside the loop, you'll add all new members in to the array.


2 Answers

It's Array.prototype.push, not Array.push

like image 54
Ven Avatar answered Nov 05 '22 00:11

Ven


You can also use [].push.apply(a, b) for shorter notation.

like image 36
erdem Avatar answered Nov 05 '22 00:11

erdem