实现数组扁平化
方法一,通过数组的flat方法
const arr = [1, [2, [3, [4, 5]]], 6]
const res1 = arr.flat(Infinity)
console.log(res1);
// 输出结果[ 1, 2, 3, 4, 5, 6 ]
方法二,利用递归和闭包
const arr = [1, [2, [3, [4, 5]]], 6]
function fn1(arr) {
let result = []
//数组定义在外层,防止在递归的时候置为空数组
function fn2(arr) {
//遍历判断数组的每一项是否为数组
arr.forEach(element => {
if (Array.isArray(element)) {
//是数组就继续调用
fn2(element)
}
else {
//不是数组就添加到result中
result.push(element)
}
})
return result
}
return fn2(arr)
}
console.log(fn1(arr));
// 输出结果[ 1, 2, 3, 4, 5, 6 ]
当然,看完你会发现没必要写成上面这样,其实非常简单
const arr = [1, [2, [3, [4, 5]]], 6]
function fn1(arr) {
let result = []
function fn2(arr) {
arr.forEach(element => {
if (Array.isArray(element)) {
fn2(element)
}
else {
result.push(element)
}
})
}
fn2(arr)
return result
}
console.log(fn1(arr));
就这样写结果也是一样的,扩展一下链式写法
const arr3 = [1, [2, [3, [4, 5]]], 6, 8]
let fn = function (arr) {
let result = []
let fn2 = function (arr) {
return new Promise((resolve, reject) => {
arr.forEach(element => {
if (Array.isArray(element)) {
fn2(element)
} else {
result.push(element)
}
})
resolve(result)
})
}
return fn2(arr)
}
fn(arr2).then(arr2 => {
console.log(arr2);
//[ 1, 2, 3, 4, 5, 6 ]
return fn(arr3)
}).then(data => {
console.log(data);
//[ 1, 2, 3, 4, 5, 6 ,8]
})
方法三,利用数组连接和扩展运算符
let fn2 = function (arr) {
while (arr.some(element => Array.isArray(element))) {
//当数组的一项是数组,那就用空数组与解构出来的新数组连接,令其继续解构
arr = [].concat(...arr)
}
}
fn2(arr3)
console.log(arr3);
//[1, 2, 3, 4, 5, 6, 8]