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

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


当前回答

另一种选择,如果你安装了lodash:

 import { merge } from 'lodash';

 var arr1 = merge(arr1, arr2);

其他回答

只需在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);

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

把答案结合起来……

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

我喜欢推。应用上面描述的(a, b)方法,如果你想,你可以创建一个这样的库函数:

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

像这样使用它

a = [1,2]
b = [3,4]

a.append(b)

可以使用splice()来实现:

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

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