如何扩展现有的JavaScript数组另一个数组? [英] How to extend an existing JavaScript array with another array?

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

问题描述

注意:这就是不是重复追加到阵列 - 这里的目标是一个阵列的全部内容添加到其他的,并做到位,即不复制扩展的阵列中的所有元素

似乎没有要与另一个阵列扩展现有的JavaScript数组的方式,即模仿Python的延长方法。

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.

我想实现的是以下内容:

What I want to achieve is the following:

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

推荐答案

的<一个href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/push\"><$c$c>.push方法可以使用​​<一个接受多个参数,所以href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/apply\"><$c$c>.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)

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

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