這樣優(yōu)化數(shù)組 mise.all,性能提升 60%
操作數(shù)組時過度使用嵌套循環(huán)會導(dǎo)致代碼難以閱讀和維護,即所謂的"循環(huán)地獄"。幸運的是,JavaScript提供了許多強大的數(shù)組方法,可以讓我們的的代碼更加簡潔、可讀,同時保持高效。
1. map() - 轉(zhuǎn)換數(shù)組元素
map()方法創(chuàng)建一個新數(shù)組,其結(jié)果是對原數(shù)組中的每個元素調(diào)用提供的函數(shù)后的返回值。
// 將數(shù)組中的每個數(shù)字翻倍
const numbers = [1, 2, 3, 4];
const doubled = numbers.map(num => num * 2);
// 結(jié)果: [2, 4, 6, 8]
2. filter() - 篩選數(shù)組元素
filter()方法創(chuàng)建一個新數(shù)組,其中包含通過所提供函數(shù)測試的所有元素。
// 篩選出所有偶數(shù)
const numbers = [1, 2, 3, 4, 5, 6];
const evens = numbers.filter(num => num % 2 === 0);
// 結(jié)果: [2, 4, 6]
3. reduce() - 累積計算
reduce()方法對數(shù)組中的每個元素執(zhí)行一個由您提供的reducer函數(shù),將其結(jié)果匯總為單個返回值。
// 計算數(shù)組元素的總和
const numbers = [1, 2, 3, 4];
const sum = numbers.reduce((total, current) => total + current, 0);
// 結(jié)果: 10
4. forEach() - 遍歷數(shù)組
forEach()方法對數(shù)組的每個元素執(zhí)行一次提供的函數(shù),但不返回新數(shù)組。
// 打印數(shù)組中的每個元素
const fruits = ['apple', 'banana', 'cherry'];
fruits.forEach(fruit => console.log(fruit));
// 輸出:
// apple
// banana
// cherry
5. find() - 查找元素
find()方法返回數(shù)組中滿足提供的測試函數(shù)的第一個元素的值,如果沒有找到,則返回undefined。
// 查找第一個大于2的數(shù)字
const numbers = [1, 2, 3, 4, 5];
const firstOver2 = numbers.find(num => num > 2);
// 結(jié)果: 3
6. some() - 檢查是否有元素滿足條件
some()方法測試數(shù)組中是否至少有一個元素通過了由提供的函數(shù)實現(xiàn)的測試。
7. every() - 檢查所有元素是否滿足條件
every()方法測試一個數(shù)組內(nèi)的所有元素是否都能通過指定函數(shù)的測試。
8. includes() - 檢查數(shù)組是否包含某個值
includes()方法確定數(shù)組中是否包含某個指定的值,并相應(yīng)地返回true或false。
9. flat() - 扁平化嵌套數(shù)組
flat()方法創(chuàng)建一個新數(shù)組,其中所有子數(shù)組元素遞歸地連接到指定深度。
10. flatMap() - 映射并扁平化
flatMap()方法首先使用映射函數(shù)映射每個元素,然后將結(jié)果扁平化為一個新數(shù)組。
11. findIndex() - 查找元素的索引
findIndex()方法返回數(shù)組中滿足提供的測試函數(shù)的第一個元素的索引。如果沒有滿足條件的元素,則返回-1。
12. slice() - 提取數(shù)組的一部分
slice()方法返回一個新的數(shù)組對象,這一對象是一個由start和end決定的原數(shù)組的淺拷貝(包括start,不包括end)。
13. 鏈式調(diào)用——組合使用方法
這些方法的真正強大之處在于它們可以鏈式調(diào)用,將多個操作組合在一起,消除多重嵌套循環(huán)的需要。
// 找出所有偶數(shù),將它們翻倍,然后計算總和
const numbers = [1, 2, 3, 4, 5, 6];
const result = numbers
.filter(num => num % 2 === 0) // [2, 4, 6]
.map(num => num * 2) // [4, 8, 12]
.reduce((sum, num) => sum + num, 0); // 24