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

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

其他回答

只需在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)); 身体{ 字体类型:等宽字体; 空白:前; }

合并两个以上数组的另一种解决方案

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

然后调用并打印为:

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

输出将是:数组[1,2,3,4,5,6,7]

可以使用splice()来实现:

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

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

我觉得最近最优雅的是:

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的回答,调用堆栈会溢出。