js数组扁平化

扁平化就是这样的: fun([1,2,[3,4]]) // [1,2,3,4]

1 function fun(array) {
2     if(!Array.isArray(array)) return array;
3     return array.reduce(
4         (result, value) => result.concat(Array.isArray(value) ? fun(value) : value),
5         []
6     );
7 }
8 console.log(fun([1,2,[2,4],[]])) // [ 1, 2, 2, 4 ]
 
let a = []
console.log(a.concat(...[1, 2, 3, [4, 5]]))
console.log(a.concat(...[1, [[2,55],9], 3, [4, 5]])) // [ 1, [ 2, 55 ], 9, 3, 4, 5 ]

...可以展开一层的数组,这里循环遍历

function fun1(arr) {
    while(arr.some(item=>Array.isArray(item))) {
        arr = [].concat(...arr);
    }
    return arr;
}

 

 

posted on 2019-02-20 23:18  西门本不吹雪  阅读(130)  评论(0编辑  收藏  举报