const arr = [1, [2, [3, [4, 5]]], 6];
====> [1, 2, 3, 4, 5, 6]
方法一:
const res1 = arr.flat(Infinity);
方法二:
const res2 = JSON.parse('[' + JSON.stringify(arr).replace(/\[|\]/g, '') + ']');
方法三:
const flatten = arr => {
return arr.reduce((pre, cur) => {
return pre.concat(Array.isArray(cur) ? flatten(cur) : cur);
}, [])
}
const res3 = flatten(arr);
方法四:
const res4 = [];
const fn = arr => {
for (let i = 0; i < arr.length; i++) {
if (Array.isArray(arr[i])) {
fn(arr[i]);
} else {
res4.push(arr[i]);
}
}
}
fn(arr)
方法五:
function flatten(arr) {
while(arr.some(item=>Array.isArray(item))) {
arr = [].concat(...arr);
}
return arr;
}
const res5 = flatten(arr)