Fork me on GitHub

js实现展开多级数组

1.递归

function steamrollArray(arr) {
    let res = []
    for (const a of arr) {
        if(a instanceof Array){
            res = res.concat(steamrollArray(a))
        }else{
            res.push(a)
        }
    }
    return res;
}

console.log(steamrollArray([1, [2], [3, [[4]]]]));// [1,2,3,4]

2.Array.prototype.flat

console.log([1, [2], [3, [[4]]]].flat(Infinity)); // [1,2,3,4]
posted @ 2020-02-13 23:48  粥里有勺糖  阅读(1189)  评论(0编辑  收藏  举报