扁平化数组
let arr = [1,2,[3,4,[5,6,[7,8]]]];
数组方法
//数组flat()方法
let flatArr = arr.flat(Infinity);
console.log(flatArr) //[1, 2, 3, 4, 5, 6, 7, 8]
console.log(arr.flat()) //[1, 2, 3, 4,[5, 6,[7, 8]]]
console.log(arr.flat(2)) //[1, 2, 3, 4, 5, 6,[7, 8]]
递归算法
function flatten(arr){
let res = [];
arr.map(item=>{
if(Array.isArray(item)){
res = res.concat(flatten(item))
}else{
res.push(item)
}
})
return res;
}
console.log(flatten(arr)) //[1, 2, 3, 4, 5, 6, 7, 8]
function flat(arr){
let result = [];
if(arr instanceof Array){
for(let i = 0;i < arr.length;i ++){
result = result.concat(flat(arr[i]))
}
}else{
result.push(arr)
}
return result;
}
console.log(flat(arr)) //[1, 2, 3, 4, 5, 6, 7, 8]