1. 程式人生 > >陣列平鋪到指定深度

陣列平鋪到指定深度


var result = [];
/**
 * @param {*} arr 陣列
 * @param {*} depth 深度
 * @returns
 */
function f(arr,depth){
    arr.map(function(item){
      if(depth){
        if(Array.isArray(item)){
          result.concat(f(item,--depth));
        }else{
          result.push(item);
        }
      }else{
        result.push(item);
      }
    })
    return result;  
}

console.log(f([1,[2,[3]]],1))