Skip to content

数组扁平化

69 字小于 1 分钟

2024-12-28

数组扁平化

 let arr = [2, 3, 4, [6, 34, [22, 33, 44], 23], 12];
 function flatNew (arr, bool) {
      let res = [];
      for (const key in arr) {
        if (arr[key] instanceof Array) {
          res = bool ? res.concat(flatNew(arr[key]), []) : res.concat(arr[key]);
        } else {
          res.push(arr[key]);
        }
      }
      return res;
    }
    let data = flatNew(arr, true);
    console.log(data);