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

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


当前回答

答案非常简单。

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

可以使用splice()来实现:

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

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

我添加了这个答案,因为尽管这个问题没有创建一个新数组,但几乎每个答案都忽略了它。

现代JavaScript可以很好地处理数组等可迭代对象。这使得在此基础上实现一个版本的concat成为可能,并在逻辑上跨越数组数据的参数。

下面的例子使用了iter-ops库,它具有这样的逻辑:

import {pipe, concat} from 'iter-ops';

const i = pipe(
    originalArray,
    concat(array2, array3, array4, ...)
); //=> Iterable

for(const a of i) {
    console.log(a); // iterate over values from all arrays
}

上面没有创建新数组。操作符concat将遍历原始数组,然后按照指定的顺序自动继续到array2、array3等等。

就内存使用而言,这是最有效的连接数组的方法。

如果在最后,你决定将它转换为一个实际的物理数组,你可以通过展开操作符或array .from来实现:

const fullArray1 = [...i]; // pulls all values from iterable, into a new array

const fullArray2 = Array.from(i); // does the same

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

 import { merge } from 'lodash';

 var arr1 = merge(arr1, arr2);

答案非常简单。

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