今天給大家分享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)
。