js实现数组扁平化输出
方法一:使用 Array.prototype.flat()
ES2019 引入的 flat() 方法可以直接将嵌套数组扁平化。默认情况下,flat() 只会扁平化一层,可以通过传入参数指定深度,或使用 Infinity 完全扁平化。
const nestedArray = [1, [2, [3, [4]], 5]];
const flattened = nestedArray.flat(Infinity);
console.log(flattened); // 输出: [1, 2, 3, 4, 5]
方法二:递归实现
通过递归遍历数组,将嵌套的数组逐层展开。适用于不支持 flat() 的老版本浏览器或需要自定义处理的情况。

function flattenArray(arr) {
let result = [];
arr.forEach(item => {
if (Array.isArray(item)) {
result.push(...flattenArray(item));
} else {
result.push(item);
}
});
return result;
}
const nestedArray = [1, [2, [3, [4]], 5]];
console.log(flattenArray(nestedArray)); // 输出: [1, 2, 3, 4, 5]
方法三:使用 reduce 实现
结合 Array.prototype.reduce 和递归,可以更简洁地实现扁平化。
function flattenArray(arr) {
return arr.reduce((acc, item) =>
acc.concat(Array.isArray(item) ? flattenArray(item) : item), []);
}
const nestedArray = [1, [2, [3, [4]], 5]];
console.log(flattenArray(nestedArray)); // 输出: [1, 2, 3, 4, 5]
方法四:利用 toString 和 split
如果数组仅包含数字或字符串,可以先将数组转换为字符串,再通过 split 分割为扁平数组。注意此方法会将所有元素转为字符串。

const nestedArray = [1, [2, [3, [4]], 5]];
const flattened = nestedArray.toString().split(',').map(Number);
console.log(flattened); // 输出: [1, 2, 3, 4, 5]
方法五:使用 Generator 函数
通过生成器函数逐层展开嵌套数组,适合处理大规模数据或需要惰性计算的场景。
function* flattenGenerator(arr) {
for (const item of arr) {
if (Array.isArray(item)) {
yield* flattenGenerator(item);
} else {
yield item;
}
}
}
const nestedArray = [1, [2, [3, [4]], 5]];
const flattened = [...flattenGenerator(nestedArray)];
console.log(flattened); // 输出: [1, 2, 3, 4, 5]
方法六:堆栈迭代实现
非递归的堆栈实现方式,避免递归可能导致的调用栈溢出问题,适合处理深层嵌套数组。
function flattenArray(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 nestedArray = [1, [2, [3, [4]], 5]];
console.log(flattenArray(nestedArray)); // 输出: [1, 2, 3, 4, 5]
注意事项
- 数据类型一致性:递归或迭代方法可能因数据类型复杂(如对象、
null)需要额外处理。 - 性能差异:
flat()是原生方法,性能通常最优;递归在大数据量时可能栈溢出。 - 浏览器兼容性:
flat()需 ES2019+ 环境,旧环境需使用 polyfill 或替代方案。






