案例
案例一
let arr=[
1,[2,9,[0,10]],3,[4,5,[6,7,8]]
]
// 由于是值的引用,所以新修改的数组,是会影响原来数组的
function cArr(arr,newarr=[]){
arr.forEach(item=>{
if(Array.isArray(item)){
cArr(item,newarr)
return
}
newarr.push(item)
})
return newarr
}
let arr1=cArr(arr)
console.log(arr1);
另一种实现
let arr = [
1, [2, 9, [0, 10]], 3, [4, 5, [6, 7, 8]]
]
function cfunc(data) {
if (!Array.isArray(data)) {
return data
}
let newarr = []
data.forEach(item => {
let data1 = cfunc(item)
if (!Array.isArray(data1)) {
newarr.push(data1)
return
}
newarr = [...newarr, ...data1]
})
return newarr
}
console.log(cfunc(arr));
案例二
arr1.flat(Infinity)
案例三
let arr1=[1,2,3,[4,5,6,[7,8],[9]],10]
function flatten3(arr){
let newarr=[...arr]
// some 有一个满足的就会返回true
while (newarr.some(item=>Array.isArray(item))){
newarr=[].concat(...newarr)
}
return newarr
}
console.log(flatten3(arr1))