[Vue中文社區(qū)](javascript:void(0);) 5月21日
英文:Una Kravets 譯文:熊賢仁
map、reduce 和 filter 是三個非常實(shí)用的 JavaScript 數(shù)組方法,賦予了開發(fā)者四兩撥千斤的能力。我們直接進(jìn)入正題,看看如何使用(并記?。┻@些超級好用的方法!
Array.map()
Array.map() 根據(jù)傳遞的轉(zhuǎn)換函數(shù),更新給定數(shù)組中的每個值,并返回一個相同長度的新數(shù)組。它接受一個回調(diào)函數(shù)作為參數(shù),用以執(zhí)行轉(zhuǎn)換過程。
<pre class="" style="margin: 0px; padding: 8px 0px 6px; max-width: 100%; box-sizing: border-box; word-wrap: break-word !important; letter-spacing: 0.544px; border-radius: 0px; overflow-y: auto; color: rgb(80, 97, 109); text-align: start; font-size: 10px; line-height: 12px; overflow-wrap: break-word !important; font-family: consolas, menlo, courier, monospace, 'Microsoft Yahei' !important; border: 1px solid rgb(226, 226, 226) !important; background: rgb(245, 247, 255);">
let newArray = oldArray.map((value, index, array) => {...});
</pre>
一個幫助記住 map 的方法:Morph Array Piece-by-Piece(逐個改變數(shù)組)
你可以使用 map 代替 for-each 循環(huán),來遍歷并對每個值應(yīng)用轉(zhuǎn)換函數(shù)。這個方法適用于當(dāng)你想更新數(shù)組的同時保留原始值。它不會潛在地刪除任何值(filter 方法會),也不會計(jì)算出一個新的輸出(就像 reduce 那樣)。map 允許你逐個改變數(shù)組。一起來看一個例子:
<pre class="" style="margin: 0px; padding: 8px 0px 6px; max-width: 100%; box-sizing: border-box; word-wrap: break-word !important; letter-spacing: 0.544px; border-radius: 0px; overflow-y: auto; color: rgb(80, 97, 109); text-align: start; font-size: 10px; line-height: 12px; overflow-wrap: break-word !important; font-family: consolas, menlo, courier, monospace, 'Microsoft Yahei' !important; border: 1px solid rgb(226, 226, 226) !important; background: rgb(245, 247, 255);">
[1, 4, 6, 14, 32, 78].map(val => val * 10)// the result is: [10, 40, 60, 140, 320, 780]
</pre>
上面的例子中,我們使用一個初始數(shù)組([1, 4, 6, 14, 32, 78]),映射每個值到它自己的十倍(val * 10)。結(jié)果是一個新數(shù)組,初始數(shù)組的每個值被這個等式轉(zhuǎn)換:[10, 40, 60, 140, 320, 780]。
Array.filter()
當(dāng)我們想要過濾數(shù)組的值到另一個數(shù)組,新數(shù)組中的每個值都通過一個特定檢查,Array.filter() 這個快捷實(shí)用的方法就派上用場了。
類似搜索過濾器,filter 基于傳遞的參數(shù)來過濾出值。
舉個例子,假定有個數(shù)字?jǐn)?shù)組,想要過濾出大于 10 的值,可以這樣寫:
<pre class="" style="margin: 0px; padding: 8px 0px 6px; max-width: 100%; box-sizing: border-box; word-wrap: break-word !important; letter-spacing: 0.544px; border-radius: 0px; overflow-y: auto; color: rgb(80, 97, 109); text-align: start; font-size: 10px; line-height: 12px; overflow-wrap: break-word !important; font-family: consolas, menlo, courier, monospace, 'Microsoft Yahei' !important; border: 1px solid rgb(226, 226, 226) !important; background: rgb(245, 247, 255);">
[1, 4, 6, 14, 32, 78].filter(val => val > 10)// the result is: [14, 32, 78]
</pre>
但是 filter 方法,只返回真值。因此如果所有值都執(zhí)行指定的檢查的話,結(jié)果的長度會小于等于原始數(shù)組。
把 filter 想象成一個漏斗。部分混合物會從中穿過進(jìn)入結(jié)果,而另一部分則會被留下并拋棄。
假設(shè)寵物訓(xùn)練學(xué)校有一個四只狗的小班,學(xué)校里的所有狗都會經(jīng)過各種挑戰(zhàn),然后參加一個分級期末考試。我們用一個對象數(shù)組來表示這些狗狗:
<pre class="" style="margin: 0px; padding: 8px 0px 6px; max-width: 100%; box-sizing: border-box; word-wrap: break-word !important; letter-spacing: 0.544px; border-radius: 0px; overflow-y: auto; color: rgb(80, 97, 109); text-align: start; font-size: 10px; line-height: 12px; overflow-wrap: break-word !important; font-family: consolas, menlo, courier, monospace, 'Microsoft Yahei' !important; border: 1px solid rgb(226, 226, 226) !important; background: rgb(245, 247, 255);">
const students = [{name: "Boops",finalGrade: 80},{name: "Kitten",finalGrade: 45},{name: "Taco",finalGrade: 100},{name: "Lucy",finalGrade: 60}]
</pre>
如果狗狗們的期末考試成績高于 70 分,它們會獲得一個精美的證書;反之,它們就要去重修。為了知道證書打印的數(shù)量,要寫一個方法來返回通過考試的狗狗。不必寫循環(huán)來遍歷數(shù)組的每個對象,我們可以用 filter 簡化代碼!
<pre class="" style="margin: 0px; padding: 8px 0px 6px; max-width: 100%; box-sizing: border-box; word-wrap: break-word !important; letter-spacing: 0.544px; border-radius: 0px; overflow-y: auto; color: rgb(80, 97, 109); text-align: start; font-size: 10px; line-height: 12px; overflow-wrap: break-word !important; font-family: consolas, menlo, courier, monospace, 'Microsoft Yahei' !important; border: 1px solid rgb(226, 226, 226) !important; background: rgb(245, 247, 255);">
const passingDogs = students.filter((student) => {return student.finalGrade >= 70})/*passingDogs = [{name: "Boops",finalGrade: 80},{name: "Taco",finalGrade: 100}]*/
</pre>
你也看到了,Boops 和 Taco 是好狗狗(其實(shí)所有狗都很不錯),它們?nèi)〉昧送ㄟ^課程的成就證書!利用箭頭函數(shù)的隱式返回特性,一行代碼就能實(shí)現(xiàn)。因?yàn)橹挥幸粋€參數(shù),所以可以刪掉箭頭函數(shù)的括號:
<pre class="" style="margin: 0px; padding: 8px 0px 6px; max-width: 100%; box-sizing: border-box; word-wrap: break-word !important; letter-spacing: 0.544px; border-radius: 0px; overflow-y: auto; color: rgb(80, 97, 109); text-align: start; font-size: 10px; line-height: 12px; overflow-wrap: break-word !important; font-family: consolas, menlo, courier, monospace, 'Microsoft Yahei' !important; border: 1px solid rgb(226, 226, 226) !important; background: rgb(245, 247, 255);">
const passingDogs = students.filter(student => student.finalGrade >= 70)/*passingDogs = [{name: "Boops",finalGrade: 80},{name: "Taco",finalGrade: 100}]*/
</pre>
Array.reduce()
reduce() 方法接受一個數(shù)組作為輸入值并返回一個值。這點(diǎn)挺有趣的。reduce 接受一個回調(diào)函數(shù),回調(diào)函數(shù)參數(shù)包括一個累計(jì)器(數(shù)組每一段的累加值,它會像雪球一樣增長),當(dāng)前值,和索引。reduce 也接受一個初始值作為第二個參數(shù):
<pre class="" style="margin: 0px; padding: 8px 0px 6px; max-width: 100%; box-sizing: border-box; word-wrap: break-word !important; letter-spacing: 0.544px; border-radius: 0px; overflow-y: auto; color: rgb(80, 97, 109); text-align: start; font-size: 10px; line-height: 12px; overflow-wrap: break-word !important; font-family: consolas, menlo, courier, monospace, 'Microsoft Yahei' !important; border: 1px solid rgb(226, 226, 226) !important; background: rgb(245, 247, 255);">
let finalVal = oldArray.reduce((accumulator, currentValue, currentIndex, array) => {...}), initalValue;
</pre>
來寫一個炒菜函數(shù)和一個作料清單:
<pre class="" style="margin: 0px; padding: 8px 0px 6px; max-width: 100%; box-sizing: border-box; word-wrap: break-word !important; letter-spacing: 0.544px; border-radius: 0px; overflow-y: auto; color: rgb(80, 97, 109); text-align: start; font-size: 10px; line-height: 12px; overflow-wrap: break-word !important; font-family: consolas, menlo, courier, monospace, 'Microsoft Yahei' !important; border: 1px solid rgb(226, 226, 226) !important; background: rgb(245, 247, 255);">
// our list of ingredients in an arrayconst ingredients = ['wine', 'tomato', 'onion', 'mushroom']// a cooking functionconst cook = (ingredient) => {returncooked ${ingredient}``}
</pre>
如果我們想要把這些作料做成一個調(diào)味汁(開玩笑的),用 reduce() 來歸約!
<pre class="" style="margin: 0px; padding: 8px 0px 6px; max-width: 100%; box-sizing: border-box; word-wrap: break-word !important; letter-spacing: 0.544px; border-radius: 0px; overflow-y: auto; color: rgb(80, 97, 109); text-align: start; font-size: 10px; line-height: 12px; overflow-wrap: break-word !important; font-family: consolas, menlo, courier, monospace, 'Microsoft Yahei' !important; border: 1px solid rgb(226, 226, 226) !important; background: rgb(245, 247, 255);">
const wineReduction = ingredients.reduce((sauce, item) => {return sauce += cook(item) + ', '}, '')// wineReduction = "cooked wine, cooked tomato, cooked onion, cooked mushroom, "
</pre>
初始值(這個例子中的 '')很重要,它決定了第一個作料能夠進(jìn)行烹飪。這里輸出的結(jié)果不太靠譜,自己炒菜時要當(dāng)心。下面的例子就是我要說到的情況:
<pre class="" style="margin: 0px; padding: 8px 0px 6px; max-width: 100%; box-sizing: border-box; word-wrap: break-word !important; letter-spacing: 0.544px; border-radius: 0px; overflow-y: auto; color: rgb(80, 97, 109); text-align: start; font-size: 10px; line-height: 12px; overflow-wrap: break-word !important; font-family: consolas, menlo, courier, monospace, 'Microsoft Yahei' !important; border: 1px solid rgb(226, 226, 226) !important; background: rgb(245, 247, 255);">
const wineReduction = ingredients.reduce((sauce, item) => {return sauce += cook(item) + ', '})// wineReduction = "winecooked tomato, cooked onion, cooked mushroom, "
</pre>
最后,確保新字符串的末尾沒有額外的空白,我們可以傳遞索引和數(shù)組來執(zhí)行轉(zhuǎn)換:
<pre class="" style="margin: 0px; padding: 8px 0px 6px; max-width: 100%; box-sizing: border-box; word-wrap: break-word !important; letter-spacing: 0.544px; border-radius: 0px; overflow-y: auto; color: rgb(80, 97, 109); text-align: start; font-size: 10px; line-height: 12px; overflow-wrap: break-word !important; font-family: consolas, menlo, courier, monospace, 'Microsoft Yahei' !important; border: 1px solid rgb(226, 226, 226) !important; background: rgb(245, 247, 255);">
const wineReduction = ingredients.reduce((sauce, item, index, array) => {sauce += cook(item)if (index < array.length - 1) {sauce += ', '}return sauce}, '')// wineReduction = "cooked wine, cooked tomato, cooked onion, cooked mushroom"
</pre>
可以用三目操作符、模板字符串和隱式返回,寫的更簡潔(一行搞定?。?/p>
<pre class="" style="margin: 0px; padding: 8px 0px 6px; max-width: 100%; box-sizing: border-box; word-wrap: break-word !important; letter-spacing: 0.544px; border-radius: 0px; overflow-y: auto; color: rgb(80, 97, 109); text-align: start; font-size: 10px; line-height: 12px; overflow-wrap: break-word !important; font-family: consolas, menlo, courier, monospace, 'Microsoft Yahei' !important; border: 1px solid rgb(226, 226, 226) !important; background: rgb(245, 247, 255);">
const wineReduction = ingredients.reduce((sauce, item, index, array) => {return (index < array.length - 1) ? sauce +={cook(item)}``
}, '')// wineReduction = "cooked wine, cooked tomato, cooked onion, cooked mushroom"
</pre>
記住這個方法的簡單辦法就是回想你怎么做調(diào)味汁:把多個作料歸約到單個。
和我一起唱起來!
我想要用一首歌來結(jié)束這篇博文,給數(shù)組方法寫了一個小調(diào),來幫助你們記憶: