# 嵌套数组的合并
- 对于 [ [], [], [], ...] 数组里嵌套数组,有个需求:将里面的数组元素都放到外层数组,变成 [ , , , ...]
- 例如:let arr = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];
- 变成:arr = [1, 2, 3, 4, 5, 6, 7, 8, 9];
倒是有几种方法:
1 // 模拟:执行(内含 10000 子数组 + 子数组有 13 个元素)的数组 2 let arr = []; 3 4 for (let i = 0; i < 10000; i++) { 5 arr.push([Math.random()*100, Math.random()*100, Math.random()*100, Math.random()*100, Math.random()*100, Math.random()*100, Math.random()*100, Math.random()*100, Math.random()*100, Math.random()*100, Math.random()*100, Math.random()*100, Math.random()*100]); 6 } 7 8 // 1. 双重循环 push,(推荐,速度最快) 9 // 用时:0.018 s 10 let newArr = []; 11 let nowTime = new Date(); 12 for (let va of arr) { 13 for (let vq of va) { 14 newArr.push(vq); 15 } 16 } 17 console.log(new Date() - nowTime, 'for'); 18 19 // 2. concat 20 // 用时:3.4 s 21 newArr = []; 22 nowTime = new Date(); 23 for (let va of arr) { 24 newArr = newArr.concat(va); 25 } 26 console.log(new Date() - nowTime, 'concat'); 27 28 // 3. es6 的深拷贝数组 (速度最慢) 29 // 用时:34 s 30 newArr = []; 31 nowTime = new Date(); 32 for (let va of arr) { 33 newArr = [...newArr, ...va]; 34 } 35 console.log(new Date() - nowTime, 'es6');