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

后端 未结 16 2118
深忆病人
深忆病人 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:01

    First a few words about apply() in JavaScript to help understand why we use it:

    The apply() method calls a function with a given this value, and arguments provided as an array.

    Push expects a list of items to add to the array. The apply() method, however, takes the expected arguments for the function call as an array. This allows us to easily push the elements of one array into another array with the builtin push() method.

    Imagine you have these arrays:

    var a = [1, 2, 3, 4];
    var b = [5, 6, 7];
    

    and simply do this:

    Array.prototype.push.apply(a, b);
    

    The result will be:

    a = [1, 2, 3, 4, 5, 6, 7];
    

    The same thing can be done in ES6 using the spread operator ("...") like this:

    a.push(...b); //a = [1, 2, 3, 4, 5, 6, 7]; 
    

    Shorter and better but not fully supported in all browsers at the moment.

    Also if you want to move everything from array b to a, emptying b in the process, you can do this:

    while(b.length) {
      a.push(b.shift());
    } 
    

    and the result will be as follows:

    a = [1, 2, 3, 4, 5, 6, 7];
    b = [];
    

提交回复
热议问题