JS 数组扁平化 flat 方法详解
JS 数组扁平化 flat 方法详解
在 JavaScript 编程中,处理多维数组是常见任务,而数组扁平化(将多维数组转换为一维数组)尤为重要。flat 方法是 ES6 引入的强大工具,能轻松实现此功能。
基本用法
flat 方法接收一个可选参数 depth,表示要扁平化的深度,默认值为 1。例如:
const arr = [1, [2, [3, 4]]];
const result = arr.flat();
console.log(result); // [1, 2, [3, 4]]
上述代码中,arr 是二维数组,调用 flat 后,第一层嵌套数组被展开。
指定深度
若想更深层次扁平化,可传递 depth 参数。比如:
const arr = [1, [2, [3, 4]]];
const result = arr.flat(2);
console.log(result); // [1, 2, 3, 4]
这里 depth 设为 2,数组被扁平化两层。
处理无穷深度
若数组嵌套深度不确定,可传 Infinity 实现完全扁平化:
const arr = [1, [2, [3, [4, [5]]]]];
const result = arr.flat(Infinity);
console.log(result); // [1, 2, 3, 4, 5]
与其他方法结合
flat 常与 map 等方法配合。例如,对数组中每个元素处理后再扁平化:
const arr = [[1, 2], [3, 4]];
const result = arr.map(subArr => subArr.map(num => num * 2)).flat();
console.log(result); // [2, 4, 6, 8]
先通过 map 对每个子数组元素翻倍,再用 flat 扁平化。
兼容性与替代方案
flat 方法在现代浏览器支持良好,但旧环境需考虑兼容性。可通过递归实现类似功能:
function flatten(arr) {
let result = [];
for (let i = 0; i < arr.length; i++) {
if (Array.isArray(arr[i])) {
result = result.concat(flatten(arr[i]));
} else {
result.push(arr[i]);
}
}
return result;
}
const arr = [1, [2, [3, 4]]];
const result = flatten(arr);
console.log(result); // [1, 2, 3, 4]
此递归函数遍历数组,若元素是数组则递归处理,否则直接添加到结果数组。
flat 方法为 JS 数组扁平化提供简洁高效方案,合理运用能提升代码质量与开发效率。无论是简单还是复杂嵌套数组,都可借助它或替代方案轻松应对。
文章版权声明:除非注明,否则均为Dark零点博客原创文章,转载或复制请以超链接形式并注明出处。

