似乎没有办法用另一个数组来扩展一个现有的JavaScript数组,即模仿Python的extend方法。

我想达到以下几点:

>>> a = [1, 2]
[1, 2]
>>> b = [3, 4, 5]
[3, 4, 5]
>>> SOMETHING HERE
>>> a
[1, 2, 3, 4, 5]

我知道有一个a.c concat(b)方法,但它创建了一个新数组,而不是简单地扩展第一个数组。我想要一个算法,有效地工作时,a明显大于b(即一个不复制a)。

注意:这不是“如何将内容追加到数组?”这里的目标是将一个数组的全部内容添加到另一个数组中,并做到“就地”,即不复制扩展数组的所有元素。


当前回答

如果你想使用jQuery,有$.merge()

例子:

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

结果:a = [1,2,3,4,5]

其他回答

可以使用splice()来实现:

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

但尽管它更丑,但并不比推快。至少在Firefox 3.0中不适用。

使用数组。extend而不是Array。推送> 150,000条记录。

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;
  };
}

答案非常简单。

>>> a = [1, 2]
[1, 2]
>>> b = [3, 4, 5]
[3, 4, 5]
>>> SOMETHING HERE
(The following code will combine the two arrays.)

a = a.concat(b);

>>> a
[1, 2, 3, 4, 5]

Concat的作用与JavaScript字符串连接非常相似。它将返回您在调用函数的数组末尾放入concat函数的参数的组合。关键是你必须把返回值赋给一个变量,否则它就会丢失。例如,

a.concat(b);  <--- This does absolutely nothing since it is just returning the combined arrays, but it doesn't do anything with it.

把答案结合起来……

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]);
        };
    }  
}

你可以创建一个polyfill for extend,如下所示。它会添加到数组中;In-place并返回自身,这样就可以链接其他方法。

如果(Array.prototype。Extend === undefined) { Array.prototype.extend = function(other) { this.push。应用(这个参数。长度> 1 ?论据:其他); 返回; }; } 函数print() { document.body.innerHTML += [].map。调用(参数,函数(项){ 返回typeof item === 'object' ?JSON.stringify(item): item; })。Join (' ') + '\n'; } document.body.innerHTML = "; Var a = [1,2,3]; Var b = [4,5,6]; 打印(“Concat”); print(“(1)”,a.concat (b)); print(“(2)”,a.concat (b)); Print ('(3)', a.c concat(4,5,6)); 打印(“\ nExtend”); print(“(1)”,a.extend (b)); print(“(2)”,a.extend (b)); Print ('(3)', a.extend(4,5,6)); 身体{ 字体类型:等宽字体; 空白:前; }