const arr = [1, 2, [[[3, 4]]]]
Array.prototype.flats=function(num,arr){
if(this===null||this.undefined)throw new Error('"Cannot read property flats of null or undefined"')
if(typeof(num)!="number"&&typeof(num)!="undefined")throw new Error('传值类型错误')
if(!Array.isArray(this))throw new Error(this+'.flat is not a function')
let other = Object(this)
let A=[]
function deeps(arrEven,num){
if(num==undefined){
for(var a=0;a<arrEven.length;a++){
if(Array.isArray(arrEven[a])){
deeps(arrEven[a],num)
}else{
A.push(arrEven[a])
}
}
}else if(num>0){
for(var a=0;a<arrEven.length;a++){
if(Array.isArray(arrEven[a])){
--num
deeps(arrEven[a],num)
}else{
A.push(arrEven[a])
}
}
}else{
A.push(arrEven)
}
}
for(var a=0;a<other.length;a++){
if(Array.isArray(other[a])){
deeps(other[a],num)
}else{
A.push(other[a])
}
}
return A
}
console.table(arr.flats()) //[1,2,3,4]
手写数组flat函数
最新推荐文章于 2023-09-08 10:39:22 发布