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

后端 未结 16 1875
深忆病人
深忆病人 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 07:47

    If you want to use jQuery, there is $.merge()

    Example:

    a = [1, 2];
    b = [3, 4, 5];
    $.merge(a,b);
    

    Result: a = [1, 2, 3, 4, 5]

    0 讨论(0)
  • 2020-11-22 07:47

    It is possible to do it using splice():

    b.unshift(b.length)
    b.unshift(a.length)
    Array.prototype.splice.apply(a,b) 
    b.shift() // Restore b
    b.shift() // 
    

    But despite being uglier it is not faster than push.apply, at least not in Firefox 3.0.

    0 讨论(0)
  • 2020-11-22 07:48

    I like the a.push.apply(a, b) method described above, and if you want you can always create a library function like this:

    Array.prototype.append = function(array)
    {
        this.push.apply(this, array)
    }
    

    and use it like this

    a = [1,2]
    b = [3,4]
    
    a.append(b)
    
    0 讨论(0)
  • 2020-11-22 07:50

    The .push method can take multiple arguments. You can use the spread operator to pass all the elements of the second array as arguments to .push:

    >>> a.push(...b)
    

    If your browser does not support ECMAScript 6, you can use .apply instead:

    >>> a.push.apply(a, b)
    

    Or perhaps, if you think it's clearer:

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

    Please note that all these solutions will fail with a stack overflow error if array b is too long (trouble starts at about 100,000 elements, depending on the browser).
    If you cannot guarantee that b is short enough, you should use a standard loop-based technique described in the other answer.

    0 讨论(0)
  • 2020-11-22 07:55

    Use Array.extend instead of Array.push for > 150,000 records.

    if (!Array.prototype.extend) {
      Array.prototype.extend = function(arr) {
        if (!Array.isArray(arr)) {
          return this;
        }
    
        for (let record of arr) {
          this.push(record);
        }
    
        return this;
      };
    }
    
    0 讨论(0)
  • 2020-11-22 07:57

    Combining the answers...

    Array.prototype.extend = function(array) {
        if (array.length < 150000) {
            this.push.apply(this, array)
        } else {
            for (var i = 0, len = array.length; i < len; ++i) {
                this.push(array[i]);
            };
        }  
    }
    
    0 讨论(0)
提交回复
热议问题