const arr = [1,2,3,[4,5,6,[7,8,9]] 平铺成一层结构[1,2,3,4,5,6,7,8,9]
1.递归
const newArr = []
function flatten(arr){
arr.forEach(item => {
if(Array.isArray(item)){
flatten(item)
return
}
newArr.push(item)
})
return newArr
}
2.reduce
function flatten(arr){
return arr.reduce((result, item) =>
result.concat(Array.isArray(item) ? flatten(item) : item ),[])
}
3.join(toString)/split
function flatten(arr){
return arr.join(',').split(',').map(item => {
return parseInt(item)
})
}