js flatten 简单实现
使用 Array.prototype.flat()
ES2019 引入的原生方法,直接展开嵌套数组。默认展开一层,可通过参数指定深度(如 Infinity 完全展开)。
const nested = [1, [2, [3]]];
const flattened = nested.flat(Infinity); // [1, 2, 3]
递归实现
遍历数组,递归处理嵌套的数组元素,合并结果。
function flatten(arr) {
return arr.reduce((acc, val) =>
Array.isArray(val) ? acc.concat(flatten(val)) : acc.concat(val),
[]);
}
const nested = [1, [2, [3]]];
console.log(flatten(nested)); // [1, 2, 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 nested = [1, [2, [3]]];
console.log(flatten(nested)); // [1, 2, 3]
使用 toString()(仅数字/字符串)
将数组转为字符串后分割(需元素为基本类型)。
const nested = [1, [2, [3]]];
const flattened = nested.toString().split(',').map(Number); // [1, 2, 3]
生成器函数
通过生成器逐层展开数组,适合处理大规模数据。

function* flattenGen(arr) {
for (const item of arr) {
Array.isArray(item) ? yield* flattenGen(item) : yield item;
}
}
const nested = [1, [2, [3]]];
const flattened = [...flattenGen(nested)]; // [1, 2, 3]






