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.)
push() The push() method adds one or more elements to the end of an array and returns the new length of the array.
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.
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.
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.
It's Array.prototype.push
, not Array.push
You can also use [].push.apply(a, b)
for shorter notation.
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