JavaScript flat() 与 flatMap()
Array.prototype.flat(depth)展平嵌套数组、flatMap先map再flat(1)一步完成、Infinity深度完全展平、展平稀疏数组跳过empty slot · 难度:入门 · +10XP
JavaScript flat() 与 flatMap() —— 数组拍平
嵌套数组可以用flat()展平。flatMap()是先map再flat(1)的快捷方式。
基本用法
// flat——展平嵌套数组
[1, [2, [3, [4]]]].flat(); // [1, 2, [3, [4]]] 默认深度1
[1, [2, [3, [4]]]].flat(2); // [1, 2, 3, [4]]
[1, [2, [3, [4]]]].flat(Infinity); // [1, 2, 3, 4] 完全展平
// flatMap——map后自动展平一层
['hello world', 'foo bar'].flatMap(s => s.split(' '));
// ['hello', 'world', 'foo', 'bar']
// 等价于 ['hello world', 'foo bar'].map(s => s.split(' ')).flat()
// 但flatMap更高效
动手练习
- 基础练习:把一个3层嵌套数组完全展平。
- 进阶应用:用flatMap实现"生成数组并展平"的操作。
- 项目实战:在数据处理管道中用flatMap替代map+flat的组合。