如何在不创建新数组的情况下用另一个数组扩展现有 JavaScript 数组
似乎没有办法用另一个数组扩展现有的 JavaScript 数组,即模拟 Python 的 extend
方法.
There doesn't seem to be a way to extend an existing JavaScript array with another array, i.e. to emulate Python's extend
method.
我想实现以下目标:
>>> a = [1, 2]
[1, 2]
>>> b = [3, 4, 5]
[3, 4, 5]
>>> SOMETHING HERE
>>> a
[1, 2, 3, 4, 5]
我知道有一个 a.concat(b)
方法,但它会创建一个新数组,而不是简单地扩展第一个数组.我想要一种在 a
明显大于 b
时有效的算法(即不复制 a
的算法).
I know there's a a.concat(b)
method, but it creates a new array instead of simply extending the first one. I'd like an algorithm that works efficiently when a
is significantly larger than b
(i.e. one that does not copy a
).
注意:这不是 如何将某些内容附加到数组? -- 这里的目标是将一个数组的全部内容添加到另一个数组,并就地"完成,即不复制所有元素扩展数组.
推荐答案
.push
方法可以接受多个参数.您可以使用 spread operator 传递所有第二个数组的元素作为 .push
的参数:
The .push
method can take multiple arguments. You can use the spread operator to pass all the elements of the second array as arguments to .push
:
>>> a.push(...b)
如果您的浏览器不支持 ECMAScript 6,您可以使用 .apply
改为:
If your browser does not support ECMAScript 6, you can use .apply
instead:
>>> a.push.apply(a, b)
或者,如果您认为它更清楚:
Or perhaps, if you think it's clearer:
>>> Array.prototype.push.apply(a,b)
请注意,如果数组 b
太长(问题从大约 100,000 个元素开始,具体取决于浏览器),所有这些解决方案都将失败并出现堆栈溢出错误.
如果您不能保证 b
足够短,则应使用另一个答案中描述的标准基于循环的技术.
Please note that all these solutions will fail with a stack overflow error if array b
is too long (trouble starts at about 100,000 elements, depending on the browser).
If you cannot guarantee that b
is short enough, you should use a standard loop-based technique described in the other answer.
相关文章