我的github

在 JavaScript 中,将三维(或更高维)数组展开成一维数组有多种方法。以下是几种常用方案,从最简单到最灵活:

方法 1:使用 flat(Infinity)(推荐)

const threeDArray = [[[1, 2], [3]], [[4, 5, 6]]];
const flatArray = threeDArray.flat(Infinity);
console.log(flatArray); // [1, 2, 3, 4, 5, 6]
  • ✅ 优点:最简洁,一行代码解决

  • ⚠️ 注意:Infinity 会递归展开任意深度的嵌套数组

方法 2:递归 + reduce

function flatten(arr) {
  return arr.reduce((acc, val) => 
    Array.isArray(val) ? acc.concat(flatten(val)) : acc.concat(val), 
  []);
}

const threeDArray = [[[1, 2], [3]], [[4, 5, 6]]];
console.log(flatten(threeDArray)); // [1, 2, 3, 4, 5, 6]

方法 3:迭代 + 栈(避免递归深度限制)

function flatten(arr) {
  const stack = [...arr];
  const result = [];
  
  while (stack.length) {
    const next = stack.pop();
    if (Array.isArray(next)) {
      stack.push(...next);
    } else {
      result.push(next);
    }
  }
  
  return result.reverse(); // 保持原始顺序
}

const threeDArray = [[[1, 2], [3]], [[4, 5, 6]]];
console.log(flatten(threeDArray)); // [1, 2, 3, 4, 5, 6]

方法 4:使用 toString() + split()(仅数字数组)

const threeDArray = [[[1, 2], [3]], [[4, 5, 6]]];
const flatArray = threeDArray.toString().split(',').map(Number);
console.log(flatArray); // [1, 2, 3, 4, 5, 6]
  • ✅ 优点:代码简短

  • ⚠️ 限制:仅适用于纯数字数组,会丢失其他数据类型


各方案对比:

方法优点缺点
flat(Infinity) 最简单原生支持 不兼容 IE/旧浏览器
递归 通用性强,可处理复杂数据 深度嵌套可能导致栈溢出
迭代栈 无递归深度限制,性能稳定 代码稍复杂,需处理顺序
toString() 代码极简 仅支持数字,会丢失数据类型

推荐选择:

  1. 现代项目首选 flat(Infinity)

  2. 需要兼容旧环境或处理复杂数据使用递归方案

  3. 超深嵌套数组(10000+层)使用迭代栈方案

测试用例:[[[1, [2]], [[[3], 4]], 5] → 所有有效方案都应返回 [1, 2, 3, 4, 5]

参考:https://chat.deepseek.com/a/chat/s/ba764f18-0ac3-4da6-88d8-dd8e962a2074

posted on 2025-07-08 15:14  XiaoNiuFeiTian  阅读(27)  评论(0)    收藏  举报