在 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]
方法 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() |
代码极简 |
仅支持数字,会丢失数据类型 |
推荐选择:
-
现代项目首选 flat(Infinity)
-
需要兼容旧环境或处理复杂数据使用递归方案
-
超深嵌套数组(10000+层)使用迭代栈方案
测试用例:[[[1, [2]], [[[3], 4]], 5] → 所有有效方案都应返回 [1, 2, 3, 4, 5]
参考:https://chat.deepseek.com/a/chat/s/ba764f18-0ac3-4da6-88d8-dd8e962a2074