js实现flat
实现数组扁平化的方法
使用递归方法实现数组扁平化。递归遍历数组中的每个元素,如果元素是数组则继续递归,否则将元素添加到结果数组中。

function flat(arr, depth = 1) {
let result = [];
arr.forEach(item => {
if (Array.isArray(item) && depth > 0) {
result.push(...flat(item, depth - 1));
} else {
result.push(item);
}
});
return result;
}
使用reduce实现扁平化
通过reduce方法遍历数组,将非数组元素直接添加到结果中,数组元素则递归处理。

function flat(arr, depth = 1) {
return depth > 0
? arr.reduce((acc, val) => acc.concat(Array.isArray(val) ? flat(val, depth - 1) : val), [])
: arr.slice();
}
使用堆栈实现非递归扁平化
通过堆栈结构实现非递归的扁平化处理,适合处理深度较大的数组。
function flat(arr, depth = 1) {
const stack = arr.map(item => ({ item, depth }));
const result = [];
while (stack.length) {
const { item, depth } = stack.pop();
if (Array.isArray(item) && depth > 0) {
stack.push(...item.map(subItem => ({ item: subItem, depth: depth - 1 })));
} else {
result.push(item);
}
}
return result.reverse();
}
使用Generator实现惰性扁平化
通过Generator函数实现按需扁平化,适合处理大规模数据。
function* flatGenerator(arr, depth = 1) {
for (const item of arr) {
if (Array.isArray(item) && depth > 0) {
yield* flatGenerator(item, depth - 1);
} else {
yield item;
}
}
}
function flat(arr, depth = 1) {
return [...flatGenerator(arr, depth)];
}
注意事项
每种实现方式都有其适用场景。递归方法简洁但可能有调用栈限制,reduce方法函数式风格明显,堆栈方法适合深度大的结构,Generator方法适合流式处理。根据实际需求选择合适的方法。






