题解 | #数组扁平化#
数组扁平化
https://www.nowcoder.com/practice/5d7e0cf4634344c98e6ae4eaa2336bed
1.利用join的可迭代性转换多重数组
const_flatten = arr => {
// 补全代码
arr.forEach((ele,index) =>
{
if(typeof ele==="object"){
arr1=ele.join(",").split(",").map((x)=>+x);
arr.splice(index,1,...arr1);
}
})
returnarr;
}
2.利用while循坏遍历多重数组
const_flatten = arr => {
// 补全代码
let count1=0;
while(true){
let count2=0;
arr.forEach((ele,index) =>
{
++count2;
if(typeof arr[index]==="object")arr.splice(index,1,...ele);
})
if(count2&&count1!=count2)console.log(count1=count2);
elseif(count1==count2)break;
}
console.log("count1:",count1)
returnarr;
}