前端小白的修炼 2019-06-28
输入:一个嵌套型数组
输出:扁平化后的数组
let array = [1, [2, 3, 4]]; let arrayDeeper = [1, [2, [3, 4]]];
function flatten_1(arr) { return Array.prototype.concat.apply([], arr); } console.log(flatten_1(array));
function flattenDeeper_1(arr) { return arr.toString().split(',').map((item) => parseInt(item)); //return arr.join(',').split(',').map((item) => parseInt(item)); } function flattenDeeper_2(arr) { return arr.reduce((prev, current) => { return Array.prototype.concat(prev, Array.isArray(current) ? flattenDeeper(current) : current); }) } function flattenDeeper_3(arr, result = []) { for (let item of arr) { if(Array.isArray(item)){ flattenDeeper_2(item, result); }else{ result.push(item); } } return result; } console.log(flattenDeeper_1(arrayDeeper)); console.log(flattenDeeper_2(arrayDeeper)); console.log(flattenDeeper_3(arrayDeeper));