实现数组的flat方法

陶博耘
2023-12-01
function _flat(arr,depth){
    let result = [];
    if(!Array.isArray(arr)||depth<=0) return arr;
    for(let i = 0; i < arr.length; i++) {
        if(Array.isArray(arr[i])) {
          result = result.concat(_flat(arr[i],depth-1));
        }
        else {
          result.push(arr[i]);
        }
    }
    return result;
  }
  let arr = [1, [2, [3, 4, 5,[9,8,[2]]]]];
  console.log(_flat(arr,Infinity));
 类似资料: