今天给大家分享ES6中两个超实用的数组函数:flat()
和flatMap()
,学会它们能让数组处理变得更轻松!
1. flat()
函数
1.1 基本介绍
flat()
用于将嵌套数组"拍平",即将多维数组转换为一维数组。
1.2 语法
const newArray = oldArray.flat([depth]);
- `depth`:可选参数,表示拍平深度,默认值为1### 1.3 示例#### 默认深度(depth=1)
```javascript
const arr = [1, [2, 3], [4, [5, 6]]];
console.log(arr.flat());
// 输出: [1, 2, 3, 4, [5, 6]]
指定深度(depth=2)
const arr = [1, [2, 3], [4, [5, 6]]];
console.log(arr.flat(2));
// 输出: [1, 2, 3, 4, 5, 6]
完全拍平(Infinity)
const arr = [1, [2, [3, [4]]]];
console.log(arr.flat(Infinity));
// 输出: [1, 2, 3, 4]
1.4 注意事项
- 自动移除空元素
console.log([1, , 3].flat()); // 输出: [1, 3]
2. flatMap()
函数
2.1 基本介绍
flatMap()
是map()
和flat(1)
的组合,先映射再拍平一层。
2.2 语法
const newArray = arr.flatMap(callback(currentValue[, index[, array]]){// 返回新数组元素
});
2.3 示例
const nums = [1, 2, 3];// 等效于map后接flat(1)
console.log(nums.flatMap(x => [x * 2]));
// 输出: [2, 4, 6]// 只能拍平一层
console.log(nums.flatMap(x => [[x * 2]]));
// 输出: [[2], [4], [6]]
2.4 实际应用
// 拆分字符串并展开
const sentences = ["Hello world", "Good morning"];
console.log(sentences.flatMap(s => s.split(' ')));
// 输出: ["Hello", "world", "Good", "morning"]
总结对比
方法 | 作用 | 拍平深度 |
---|---|---|
flat() | 单纯拍平数组 | 可指定 |
flatMap() | 先map再flat(1) | 固定1层 |
这两个方法在处理嵌套数组时非常有用,合理使用可以让代码更简洁高效!
小贴士:遇到复杂嵌套结构时,可以组合使用
map
+flat
或直接使用flat(Infinity)
。