有时候会遇到一个数组里边有多个数组的状况(多维数组),而后你想把它拉平使其成为一个一维数组,其实最简单的一个方法就是ES6数组方法Array.prototype.flat。使用方法以下:数组
const lists = [1, [2, 3, [4, 5]]]; lists.flat(); // [1, 2, 3, [4, 5]],默认只拉平一层,若是想要所有拉平,参数换为Infinity便可
但是实际有些状况下,须要去兼容低版本的问题处理,因此就本身写了两种解决方案,根据本身喜欢使用,不过没支持Infinity这个处理方式,仅是做为自定义拉平数组。prototype
1.递归code
const lists = [1, [2, 3, [4, 5]]]; function reduceArr(list, depth) { if(depth === 0) return list; let result = []; for(let i = 0;i < list.length;i++) { if(Array.isArray(list[i])) { result = result.concat(list[i]); } else { result.push(list[i]); } } return reduceArr(result, --depth); } console.log(reduceArr(lists, 2));
2.循环处理递归
const lists = [1, [2, 3, [4, 5]]]; function reduceArr(list, depth) { let result = []; for(let i = 1;i <= depth;i++) { result.length && (list = result); result = []; for(let j = 0;j < list.length;j++) { if(Array.isArray(list[j])) { result = result.concat(list[j]); } else { result.push(list[j]); } } } if(depth) { return result; } else { return list; } } console.log(reduceArr(lists, 2));