[1, 2, 3, [4, 5, 6, [7, 8], 9], 10] => [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

reduce + concat

1
2
3
4
5
6
function flattenDeep(arr) {
return arr.reduce((acc, curr) => Array.isArray(curr) ? acc.concat(flattenDeep(curr)) : acc.concat(curr), [])
}

let a = [1, 2, 3, [4, 5, 6, [7, 8], 9], 10]
console.log(flattenDeep(a))

toString

1
2
3
4
5
6
function flattenDeep(arr) {
return arr.toString().split(",").map(item => Number(item))
}

let a = [1, 2, 3, [4, 5, 6, [7, 8], 9], 10]
console.log(flattenDeep(a))

这是什么高级方法 !!!

forEach

1
2
3
4
5
6
7
8
9
10
11
12
13
14
function flattenDeep(arr) {
let res = []
arr.forEach(item => {
if (Array.isArray(item)) {
res = res.concat(flattenDeep((item)))
} else {
res.push(item)
}
})
return res
}

let a = [1, 2, 3, [4, 5, 6, [7, 8], 9], 10]
console.log(flattenDeep(a))

原理跟reduce的一样, 应该说 reduce 的原理跟这个一样