const arr = [1, [2, [3, [4, 5]]]];

function flatten(arr) {
  const res = [];
  arr.forEach((item) => {
    if (Array.isArray(item)) {
      res.push(...flatten(item));
    } else {
      res.push(item);
    }
  });

  return res;
}

function flatten2(arr) {
  while (arr.some((item) => Array.isArray(item))) {
    arr = [].concat(...arr);
  }
  return arr;
}

console.log(flatten(arr));
console.log(flatten2(arr));
最后修改:2022 年 08 月 11 日 03 : 01 PM
如果觉得我的文章对你有用,请随意赞赏