递归实现flat()

203 阅读1分钟
const arr = [1, 2, [3, 4, [5, 6, [7, 8]]]]
//array为要降维的数组。depth为降维的次数
function myFlat(array, depth = 1) {
  //判断参数是否正确传递
  if (!(array instanceof Array) || depth < 1 || depth % 1 !== 0) {
    throw new Error('请正确传递参数!')
  }
  //定义返回值数组
  const result = []
  //记录递归次数
  let count = 0
  //定义递归函数
  function _flat(arr) {
    for (const item of arr) {
      //判断条件是否要进行递归
      if (item instanceof Array && count < depth) {
        count++
        _flat(item)
      } else {
        result.push(item)
      }
    }
  }
  _flat(array)
  return result
}
console.log(myFlat(arr, 2))