How to extend an existing JavaScript array with another array, without creating a new array

后端 未结 16 1904
深忆病人
深忆病人 2020-11-22 07:38

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

16条回答
  •  一生所求
    2020-11-22 08:03

    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.

提交回复
热议问题