There doesn\'t seem to be a way to extend an existing JavaScript array with another array, i.e. to emulate Python\'s extend
method.
I want to achieve th
I feel the most elegant these days is:
arr1.push(...arr2);
The MDN article on the spread operator mentions this nice sugary way in ES2015 (ES6):
A better push
Example: push is often used to push an array to the end of an existing array. In ES5 this is often done as:
var arr1 = [0, 1, 2]; var arr2 = [3, 4, 5]; // Append all items from arr2 onto arr1 Array.prototype.push.apply(arr1, arr2);
In ES6 with spread this becomes:
var arr1 = [0, 1, 2]; var arr2 = [3, 4, 5]; arr1.push(...arr2);
Do note that arr2
can't be huge (keep it under about 100 000 items), because the call stack overflows, as per jcdude's answer.