Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
256 views
in Technique[技术] by (71.8m points)

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

There doesn't seem to be a way to extend an existing JavaScript array with another array, ie to emulate Python's extend method.(似乎没有办法用另一个数组扩展现有的JavaScript数组,即模拟Python的extend方法。)

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.(我知道有一个a.concat(b)方法,但它创建了一个新数组,而不是简单地扩展第一个数组。)

I'd like an algorithm that works efficiently when a is significantly larger than b (ie one that does not copy a ).(我想要一个算法,当a明显大于b (即不复制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", ie without copying all elements of the extended array.( - 这里的目标是将一个数组的全部内容添加到另一个数组中,并“就地”执行,即不复制扩展数组的所有元素。)   ask by DzinX translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The .push method can take multiple arguments.(.push方法可以使用多个参数。)

You can use the spread operator to pass all the elements of the second array as arguments to .push :(您可以使用spread运算符将第二个数组的所有元素作为参数传递给.push :)
>>> a.push(...b)

If your browser does not support ECMAScript 6, you can use .apply instead:(如果您的浏览器不支持ECMAScript 6,则可以使用.apply :)

>>> 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).(请注意,如果阵列b太长,所有这些解决方案都会因堆栈溢出错误而失败(麻烦从大约100,000个元素开始,具体取决于浏览器)。)

If you cannot guarantee that b is short enough, you should use a standard loop-based technique described in the other answer.(如果你不能保证b足够短,你应该使用另一个答案中描述的基于循环的标准技术。)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...