似乎没有办法用另一个数组来扩展一个现有的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)。

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


当前回答

只需在push()方法的帮助下向数组添加新元素就可以做到这一点。

let colors = ["Red", "Blue", "Orange"]; console.log(' push前数组:' + colors); //添加新值到数组 colors.push(“绿色”); console.log(' push后数组:' + colors);

另一个用于将元素追加到数组开头的方法是unshift()函数,它添加并返回新的长度。它接受多个参数,附加现有元素的索引,最后返回数组的新长度:

let colors = ["Red", "Blue", "Orange"]; console.log(' unshift前数组:' + colors); //添加新值到数组 颜色。未(“黑色”,“绿色”); console.log(' unshift后的数组:' + colors);

还有其他方法。你可以在这里查看。

其他回答

你可以创建一个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)); 身体{ 字体类型:等宽字体; 空白:前; }

答案非常简单。

>>> 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.

我觉得最近最优雅的是:

arr1.push(...arr2);

MDN上关于扩展操作符的文章在ES2015 (ES6)中提到了这种漂亮的甜美方式:

更好的推动 示例:push通常用于将一个数组推入到现有数组的末尾 数组中。在ES5中,这通常是这样做的: Var arr1 = [0,1,2]; Var arr2 = [3,4,5]; //将arr2中的所有项追加到arr1 Array.prototype.push。应用(arr1 arr2); 在ES6中,这变成: Var arr1 = [0,1,2]; Var arr2 = [3,4,5]; arr1.push(…arr2);

请注意arr2不能太大(保持在大约100,000项以下),因为根据jcdude的回答,调用堆栈会溢出。

首先介绍一下JavaScript中的apply(),帮助我们理解为什么要使用它:

apply()方法调用具有给定此值的函数,并且 作为数组提供的参数。

Push需要一个要添加到数组的项列表。然而,apply()方法将函数调用的预期参数作为一个数组。这允许我们使用内置的push()方法轻松地将一个数组的元素推入另一个数组。

假设你有这些数组:

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

简单地这样做:

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

结果将是:

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

同样的事情可以在ES6中使用扩展操作符("…")完成,就像这样:

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

更短更好,但目前不是所有浏览器都完全支持。

同样,如果你想把所有的东西从数组b移动到a,在这个过程中清空b,你可以这样做:

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

结果如下:

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

使用数组。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;
  };
}