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

查看:27
本文介绍了如何使用另一个数组扩展现有的 JavaScript 数组,而无需创建新数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

似乎没有办法用另一个数组扩展现有的 JavaScript 数组,即模拟 Python 的 extend 方法.

我想实现以下目标:

<预><代码>>>>a = [1, 2][1, 2]>>>b = [3, 4, 5][3, 4, 5]>>>这里的东西>>>一种[1, 2, 3, 4, 5]

我知道有一个 a.concat(b) 方法,但它创建了一个新数组,而不是简单地扩展第一个数组.我想要一种算法,当 a 明显大于 b(即不复制 a 的算法)时,它可以有效工作.

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

解决方案

.push 方法可以接受多个参数.您可以使用 spread operator 来传递所有第二个数组的元素作为 .push 的参数:

<预><代码>>>>a.push(...b)

如果您的浏览器不支持 ECMAScript 6,您可以使用 .apply 代替:

<预><代码>>>>a.push.apply(a, b)

或者,如果您认为它更清楚:

<预><代码>>>>Array.prototype.push.apply(a,b)

请注意,如果数组 b 太长(问题从大约 100,000 个元素开始,取决于浏览器),所有这些解决方案都将失败并出现堆栈溢出错误.
如果您不能保证 b 足够短,您应该使用另一个答案中描述的基于循环的标准技术.

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.

I want to achieve the following:

>>> a = [1, 2]
[1, 2]
>>> b = [3, 4, 5]
[3, 4, 5]
>>> SOMETHING HERE
>>> a
[1, 2, 3, 4, 5]

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.

解决方案

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)

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)

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天全站免登陆