如何将数组扁平化,从[1,2,[3,4,[5,6]]]=>[1,2,3,4,5,6]呢?
const arr = [ [0, 1, ['dd', 'ss']], {
test: 1
},
[3, 4, 5, [6, 7, 8, 9, 10]], 11, 12, [13, 14, 15]
]
const flat = (arr, depth) => {
// depth:扁平化的深度,默认是无限深度
const temp = []
const travel = (arr, h = 0) => {
if (Array.isArray(arr) && arr.length > 0 && (!depth || h < depth)) { // 递归终结
h++ // 每往下深入一层就加一
arr.forEach(n => { // 深度优先遍历
travel(n, h)
})
h-- // 每次回溯就减一
} else {
// console.log(h)
temp.push(arr)
}
}
travel(arr)
return temp
}
console.log(flat(arr, 2))