[Vue中文社區(qū)](javascript:void(0);) 5月21日
英文:Una Kravets 譯文:熊賢仁
map戈轿、reduce 和 filter 是三個(gè)非常實(shí)用的 JavaScript 數(shù)組方法励饵,賦予了開(kāi)發(fā)者四兩撥千斤的能力有滑。我們直接進(jìn)入正題逆害,看看如何使用(并記捉稀)這些超級(jí)好用的方法惠猿!
Array.map()
Array.map() 根據(jù)傳遞的轉(zhuǎn)換函數(shù),更新給定數(shù)組中的每個(gè)值负间,并返回一個(gè)相同長(zhǎng)度的新數(shù)組偶妖。它接受一個(gè)回調(diào)函數(shù)作為參數(shù)姜凄,用以執(zhí)行轉(zhuǎn)換過(guò)程。
<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>
一個(gè)幫助記住 map 的方法:Morph Array Piece-by-Piece(逐個(gè)改變數(shù)組)
你可以使用 map 代替 for-each 循環(huán)趾访,來(lái)遍歷并對(duì)每個(gè)值應(yīng)用轉(zhuǎn)換函數(shù)态秧。這個(gè)方法適用于當(dāng)你想更新數(shù)組的同時(shí)保留原始值。它不會(huì)潛在地刪除任何值(filter 方法會(huì))扼鞋,也不會(huì)計(jì)算出一個(gè)新的輸出(就像 reduce 那樣)申鱼。map 允許你逐個(gè)改變數(shù)組。一起來(lái)看一個(gè)例子:
<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>
上面的例子中云头,我們使用一個(gè)初始數(shù)組([1, 4, 6, 14, 32, 78])捐友,映射每個(gè)值到它自己的十倍(val * 10)。結(jié)果是一個(gè)新數(shù)組溃槐,初始數(shù)組的每個(gè)值被這個(gè)等式轉(zhuǎn)換:[10, 40, 60, 140, 320, 780]楚殿。
Array.filter()
當(dāng)我們想要過(guò)濾數(shù)組的值到另一個(gè)數(shù)組,新數(shù)組中的每個(gè)值都通過(guò)一個(gè)特定檢查竿痰,Array.filter() 這個(gè)快捷實(shí)用的方法就派上用場(chǎng)了脆粥。
類(lèi)似搜索過(guò)濾器,filter 基于傳遞的參數(shù)來(lái)過(guò)濾出值影涉。
舉個(gè)例子变隔,假定有個(gè)數(shù)字?jǐn)?shù)組,想要過(guò)濾出大于 10 的值蟹倾,可以這樣寫(xiě):
<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é)果的長(zhǎng)度會(huì)小于等于原始數(shù)組肌厨。
把 filter 想象成一個(gè)漏斗。部分混合物會(huì)從中穿過(guò)進(jìn)入結(jié)果豁陆,而另一部分則會(huì)被留下并拋棄柑爸。
假設(shè)寵物訓(xùn)練學(xué)校有一個(gè)四只狗的小班,學(xué)校里的所有狗都會(huì)經(jīng)過(guò)各種挑戰(zhàn)盒音,然后參加一個(gè)分級(jí)期末考試表鳍。我們用一個(gè)對(duì)象數(shù)組來(lái)表示這些狗狗:
<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>
如果狗狗們的期末考試成績(jī)高于 70 分,它們會(huì)獲得一個(gè)精美的證書(shū)祥诽;反之譬圣,它們就要去重修。為了知道證書(shū)打印的數(shù)量雄坪,要寫(xiě)一個(gè)方法來(lái)返回通過(guò)考試的狗狗厘熟。不必寫(xiě)循環(huán)來(lái)遍歷數(shù)組的每個(gè)對(duì)象,我們可以用 filter 簡(jiǎ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 passingDogs = students.filter((student) => {
return student.finalGrade >= 70
})
/*
passingDogs = [
{
name: "Boops",
finalGrade: 80
},
{
name: "Taco",
finalGrade: 100
}
]
*/
</pre>
你也看到了绳姨,Boops 和 Taco 是好狗狗(其實(shí)所有狗都很不錯(cuò))颇玷,它們?nèi)〉昧送ㄟ^(guò)課程的成就證書(shū)!利用箭頭函數(shù)的隱式返回特性就缆,一行代碼就能實(shí)現(xiàn)帖渠。因?yàn)橹挥幸粋€(gè)參數(shù),所以可以刪掉箭頭函數(shù)的括號(hào):
<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() 方法接受一個(gè)數(shù)組作為輸入值并返回一個(gè)值竭宰。這點(diǎn)挺有趣的空郊。reduce 接受一個(gè)回調(diào)函數(shù),回調(diào)函數(shù)參數(shù)包括一個(gè)累計(jì)器(數(shù)組每一段的累加值切揭,它會(huì)像雪球一樣增長(zhǎng))狞甚,當(dāng)前值,和索引廓旬。reduce 也接受一個(gè)初始值作為第二個(gè)參數(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>
來(lái)寫(xiě)一個(gè)炒菜函數(shù)和一個(gè)作料清單:
<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 array
const ingredients = ['wine', 'tomato', 'onion', 'mushroom']
// a cooking function
const cook = (ingredient) => {
return
cooked ${ingredient}``}
</pre>
如果我們想要把這些作料做成一個(gè)調(diào)味汁(開(kāi)玩笑的)哼审,用 reduce() 來(lái)歸約!
<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>
初始值(這個(gè)例子中的 '')很重要孕豹,它決定了第一個(gè)作料能夠進(jìn)行烹飪涩盾。這里輸出的結(jié)果不太靠譜,自己炒菜時(shí)要當(dāng)心励背。下面的例子就是我要說(shuō)到的情況:
<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>
最后春霍,確保新字符串的末尾沒(méi)有額外的空白,我們可以傳遞索引和數(shù)組來(lái)執(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>
可以用三目操作符叶眉、模板字符串和隱式返回址儒,寫(xiě)的更簡(jiǎ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) => {
return (index < array.length - 1) ? sauce +=
{cook(item)}``
}, '')
// wineReduction = "cooked wine, cooked tomato, cooked onion, cooked mushroom"
</pre>
記住這個(gè)方法的簡(jiǎn)單辦法就是回想你怎么做調(diào)味汁:把多個(gè)作料歸約到單個(gè)衅疙。
和我一起唱起來(lái)莲趣!
我想要用一首歌來(lái)結(jié)束這篇博文,給數(shù)組方法寫(xiě)了一個(gè)小調(diào)饱溢,來(lái)幫助你們記憶: