数组压平(flat)

/**
* 数组压平
*/
const flatByWhile = (arr = [1,[2,4],[4], [43,2,[444,1,[54]]], [22,3,[4]], 32], deep = 1) => {
    while(arr.some(Array.isArray) && deep > 0){
        /**
         * concat方法会将元素为数组的值解构一次
         * arr = [...arr]错误方式
         */
        arr = [].concat(...arr)
        deep--
    }
    return arr
}

const flatByRecursion = (arr = [1,[2,4],[4], [43,2,[444,1,[54]]], [22,3,[4]], 32]) => {
    let result = []
    for(let i = 0; i < arr.length; i++){
        const item = arr[i]
        if(Array.isArray(item) && deep > 0){
            result = [...result, ...flat(item, deep)]
        }else{
            result.push(item)
        }
    }
    return result
}

  添加到原型

Array.prototype.myselfFlat = function(deep = 1) {
    let origin = this
    while(origin.some(Array.isArray) && deep > 0){
        origin = [].concat(...origin)
        deep--
    }
    return origin
}

  

posted @ 2020-07-19 23:17  671_MrSix  阅读(107)  评论(0编辑  收藏  举报