從 ES2019 中開始引入了一種扁平化陣列的新方法,可以展平任何深度的陣列,
flat
flat() 方法創建一個新陣列,其中所有子陣列元素以遞回方式連接到特定深度,
語法:array.flat(depth)
- array :
flat()方法將在給定的陣列中使用, - depth:可選引數,指定展平的深度,默認情況下,深度為
1,
此方法會按照一個可指定的深度遞回遍歷陣列,并將所有元素與遍歷到的子陣列中的元素合并為一個新陣列回傳,
const arr = [[1, 2], [3, 4], 5];
console.log(arr.flat()); // [ 1, 2, 3, 4, 5 ]
flat() 方法也會移除陣列中的空項:
const arr = [[1, 2], , [3, 4], 5];
console.log(arr.flat()); // [ 1, 2, 3, 4, 5 ]
在一些復雜的場合,陣列的層級不單一比較復雜的情況下,不必去逐個計算陣列的嵌套深度,可以借助引數
Infinity,就可以將所有層級的陣列展平,
const arrVeryDeep = [[1, [2, 2, [3, [4, [5, [6]]]]], 1]];
console.log(arrVeryDeep.flat(Infinity)); // [ 1, 2, 2, 3, 4, 5, 6, 1 ]
flatMap
flatMap() 方法首先使用映射函式映射每個元素,然后將結果壓縮成一個新陣列,它與 map 連著深度值為 1 的 flat() 幾乎相同,但 flatMap() 通常在合并成一種方法的效率稍微高一些,
語法
// Arrow function
flatMap((currentValue) => { ... } )
flatMap((currentValue, index) => { ... } )
flatMap((currentValue, index, array) => { ... } )
// Callback function
flatMap(callbackFn)
flatMap(callbackFn, thisArg)
// Inline callback function
flatMap(function(currentValue) { ... })
flatMap(function(currentValue, index) { ... })
flatMap(function(currentValue, index, array){ ... })
flatMap(function(currentValue, index, array) { ... }, thisArg)
- callbackFn:處理新陣列元素的回呼函式,接收三個引數
- currentValue:陣列中正在處理的當前元素,
- index:可選引數,陣列中正在處理的當前元素的索引,
- array:可選引數,呼叫了陣列
map(),
- thisArg:執行
callbackFn時用作this的值
此方法回傳一個新陣列的值,其中每個元素都是通過回呼函式的處理過的結果,并將其展平到深度為 1,
const userRunning1 = {
movements: [1000, 4500, 500, 1200],
};
const userRunning2 = {
movements: [2000, 4500, 2500, 12000],
};
const userRunning3 = {
movements: [10000, 5000, 1500, 800],
};
const allRunning = [userRunning1, userRunning2, userRunning3];
// flat
const overalDistance = allRunning
.map((acc) => acc.movements)
.flat()
.reduce((acc, mov) => acc + mov, 0);
console.log(overalDistance); // 45500
// flatMap
const overalDistance2 = allRunning
.flatMap((acc) => acc.movements)
.reduce((acc, mov) => acc + mov, 0);
console.log(overalDistance2); // 45500
上述代碼通過 flat() 方法和 flatMap() 方法來解決同樣問題,將所有用戶的跑步記錄進行累加,
flatMap()展平的深度值為1,而flat()可以指定多級,
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/555403.html
標籤:其他
下一篇:返回列表
