写一个函数实现Array.prototype.falt。
例子
const arr = [1, [2], [3, [4]]];
flat(arr)
// [1, 2, 3, [4]]
flat(arr, 1)
// [1, 2, 3, [4]]
flat(arr, 2)
// [1, 2, 3, 4]
答案
//递归
function flat(arr,depth=1){
return depth ? arr.reduce((acc,item) => {
return [...acc,...(Array.isArray(item) ? flat(item,depth-1) : [item])]
},[])
: arr
}
//非递归
function flat(arr,depth=1){
let res=[];
let stock=arr.map((item) => [item,depth]);
while(stock.length){
let [top,depth]=stock.pop();
if(depth && Array.isArray(top)){
stock.push(...top.map((item) => [item,depth-1]))
}else{
res.push(top);
}
}
return res.reverse();
}
//尝试半天用正则表达式写,但好像并不可行