本文共 853 字,大约阅读时间需要 2 分钟。
Suppose you have two arrays:
假设您有两个数组:
const first = ['one', 'two']const second = ['three', 'four']
and you want to merge them into one single array
您想将它们合并为一个数组
How can you do so?
你该怎么做?
The modern way is to use the destructuring operator, to create a brand new array:
现代方法是使用解构运算符来创建全新的数组:
const result = [...first, ...second]
This is what I recommend. Note that this operator was introduced in ES6, so older browsers (read: Internet Explorer) might not support it.
这就是我的建议。 请注意,此运算符是ES6中引入的,因此较旧的浏览器(阅读:Internet Explorer)可能不支持它。
If you want a solution that works also with older browsers, you could use the concat()
method which can be called on any array:
如果您想要一个适用于较旧浏览器的解决方案,则可以使用concat()
方法,该方法可以在任何数组上调用:
const result = first.concat(second)
Both methods will generate a new array, without modifying the existing ones.
两种方法都将生成一个新数组,而不修改现有数组。
翻译自:
转载地址:http://hlqgb.baihongyu.com/