题解 | #数组扁平化#

数组扁平化

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;

}

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务