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

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

    Another solution to merge more than two arrays

    var a = [1, 2],
        b = [3, 4, 5],
        c = [6, 7];
    
    // Merge the contents of multiple arrays together into the first array
    var mergeArrays = function() {
     var i, len = arguments.length;
     if (len > 1) {
      for (i = 1; i < len; i++) {
        arguments[0].push.apply(arguments[0], arguments[i]);
      }
     }
    };
    

    Then call and print as:

    mergeArrays(a, b, c);
    console.log(a)
    

    Output will be: Array [1, 2, 3, 4, 5, 6, 7]

提交回复
热议问题