如何使用另一个数组扩展现有JavaScript数组,而无需创建新数组 [英] How to extend an existing JavaScript array with another array, without creating a new array

查看:160
本文介绍了如何使用另一个数组扩展现有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).

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

Note: This is not a duplicate of How to append something to an array? -- the goal here is to add the whole contents of one array to the other, and to do it "in place", i.e. without copying all elements of the extended array.

推荐答案

.push 方法可以使用多个参数,因此使用 .apply 将第二个数组的所有元素传递为参数 .push ,你可以得到你想要的结果:

The .push method can take multiple arguments, so by using .apply to pass all the elements of the second array as arguments to .push, you can get the result you want:

>>> a.push.apply(a, b)

或许,如果你认为它更清楚:

Or perhaps, if you think it's clearer:

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

如果您的浏览器支持ECMAScript 6,您可以使用更紧凑的传播运营商优雅:

If your browser supports ECMAScript 6, you can use the spread operator, which is more compact and elegant:

>>> a.push(...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.

这篇关于如何使用另一个数组扩展现有JavaScript数组,而无需创建新数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆