2026-05-11 14:32:01
在 JavaScript 中,可以使用数组的 flat() 方法快速展平嵌套数组。该方法通过指定展平深度参数,将多维数组转换为一维数组。
flat() 方法的基本用法flat() 方法接受一个可选参数 depth,用于指定展平的层数:
处理 API 返回的嵌套数据某些 API 返回的数据可能包含多层嵌套数组,使用 flat(Infinity) 可快速转换为一维结构。
树形结构线性化将树形数据(如目录结构)展平为线性数组,便于搜索或过滤。
简化复杂数组操作例如合并多个用户的兴趣爱好列表:
const users = [ { name: 'Alice', interests: ['reading', 'music'] }, { name: 'Bob', interests: ['sports', ['hiking', 'swimming']] }, { name: 'Charlie', interests: ['coding'] }];const allInterests = users.map(user => user.interests).flat(Infinity);console.log(allInterests); // 输出: ["reading", "music", "sports", "hiking", "swimming", "coding"]兼容性:flat() 是 ES2019 引入的,旧版浏览器(如 IE)不支持。可通过以下方式兼容:
Polyfill:引入核心 - JS 等库提供兼容实现。
手动递归:function flatten(arr, depth = 1) { return depth > 0 ? arr.reduce((acc, val) => acc.concat(Array.isArray(val) ? flatten(val, depth - 1) : val), []) : arr.slice();}
其他展平方法:
reduce() + concat()(仅展平一层):const arr = [1, [2, 3], [4, 5]];const flattened = arr.reduce((acc, val) => acc.concat(val), []);
apply() + concat()(同样仅一层):const flattened = [].concat.apply([], arr);
flat() 是 JavaScript 中展平嵌套数组的高效工具,通过调整 depth 参数可灵活控制展平层级。其典型应用包括处理 API 数据、转换树形结构及简化数组操作。对于旧环境,可通过 polyfill 或递归函数实现兼容。