无指定层数:扁平化数组
function flat(arr) {
let result = [];
arr.forEach(item => {
if (Array.isArray(item)) {
result = result.concat(arguments.callee(item));
} else {
result.push(item);
}
});
return result;
}
console.log(flat(arr))
let arr = [1,[3,4,[45]]];
function flat(arr) {
let result = [];
arr.forEach(item => {
if (Array.isArray(item)) {
result.push(...arguments.callee(item));
} else {
result.push(item);
}
});
return result;
}
console.log(flat(arr));
reduce实现flat
let arr = [24,6,[12,[4]]]
function flat(arr,num=1){
return num > 0
? arr.reduce((pre, cur) =>
pre.concat(Array.isArray(cur)? flat(cur,num-1) : cur),[])
:arr.slice();
}
console.log(flat(arr,1))