dan*_*y74 31 javascript ecmascript-6
我们都知道你可以这样做:
let arr1 = [1,2,3];
let arr2 = [3,4,5];
let arr3 = [...arr1, ...arr2]; // [1,2,3,3,4,5]
Run Code Online (Sandbox Code Playgroud)
但是,如何使这种动态连接N阵列?
Bri*_*hon 47
一种选择是使用reduce:
let arrs = [[1, 2], [3, 4], [5, 6]];
arrs.reduce((a, b) => [...a, ...b], []);
Run Code Online (Sandbox Code Playgroud)
当然,这是一个缓慢的解决方案(二次时间).或者,如果您可以使用Lodash,您可以_.flatten完全按照自己的意愿行事,并且更有效(线性时间).
编辑
或者,改编自下面的Xotic750评论,
[].concat(...arrs);
Run Code Online (Sandbox Code Playgroud)
哪个应该是有效的(线性时间).
aco*_*ell 14
另一个选择可能是:
const nArrays = [
[1, 2, 3, 4, 5],
[6, 7, 8, 9],
[10, 11]
];
const flattened = [].concat(...nArrays);
console.log(flattened)Run Code Online (Sandbox Code Playgroud)
小智 7
let fruits = ["apples", "bananas", "pears"];
let vegetables = ["corn", "potatoes", "carrots"];
let produce = [...fruits, ...vegetables];
console.log(produce);Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
33455 次 |
| 最近记录: |