使用ES6 Spread合并多个数组 [英] Using es6 spread to concat multiple arrays
本文介绍了使用ES6 Spread合并多个数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我们都知道您可以做到:
We all know you can do:
let arr1 = [1,2,3];
let arr2 = [3,4,5];
let arr3 = [...arr1, ...arr2]; // [1,2,3,3,4,5]
但是如何使它动态地连接N个数组?
But how do you make this dynamic to concat N arrays?
推荐答案
一种选择是使用reduce
:
let arrs = [[1, 2], [3, 4], [5, 6]];
arrs.reduce((a, b) => [...a, ...b], []);
当然,这是一个缓慢的解决方案(二次时间).另外,如果您可以使用Lodash,则_.flatten
会完全按照您的要求进行操作,并且效率更高(线性时间).
Of course, this is a slow solution (quadratic time). Alternatively, if you can use Lodash, _.flatten
does exactly what you want, and does it more efficiently (linear time).
编辑
或者,根据以下Xotic750的评论改编,
Or, adapted from Xotic750's comment below,
[].concat(...arrs);
应该有效率的(线性时间).
Which should be efficient (linear time).
这篇关于使用ES6 Spread合并多个数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文