Map卦方、Reduce 和 Filter 數(shù)組方法

[Vue中文社區(qū)](javascript:void(0);) 5月21日

英文:Una Kravets 譯文:熊賢仁

https://juejin.im/post/5caf030d6fb9a068736d2d7c

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);">

  1. let newArray = oldArray.map((value, index, array) => {

  2. ...

  3. });

</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. [1, 4, 6, 14, 32, 78].map(val => val * 10)

  2. // 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]楚殿。

image

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. [1, 4, 6, 14, 32, 78].filter(val => val > 10)

  2. // the result is: [14, 32, 78]

</pre>

但是 filter 方法匣缘,只返回真值。因此如果所有值都執(zhí)行指定的檢查的話鲜棠,結(jié)果的長(zhǎng)度會(huì)小于等于原始數(shù)組肌厨。

把 filter 想象成一個(gè)漏斗。部分混合物會(huì)從中穿過(guò)進(jìn)入結(jié)果豁陆,而另一部分則會(huì)被留下并拋棄柑爸。

image

假設(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);">

  1. const students = [

  2. {

  3. name: "Boops",

  4. finalGrade: 80

  5. },

  6. {

  7. name: "Kitten",

  8. finalGrade: 45

  9. },

  10. {

  11. name: "Taco",

  12. finalGrade: 100

  13. },

  14. {

  15. name: "Lucy",

  16. finalGrade: 60

  17. }

  18. ]

</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);">

  1. const passingDogs = students.filter((student) => {

  2. return student.finalGrade >= 70

  3. })

  4. /*

  5. passingDogs = [

  6. {

  7. name: "Boops",

  8. finalGrade: 80

  9. },

  10. {

  11. name: "Taco",

  12. finalGrade: 100

  13. }

  14. ]

  15. */

</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);">

  1. const passingDogs = students.filter(student => student.finalGrade >= 70)

  2. /*

  3. passingDogs = [

  4. {

  5. name: "Boops",

  6. finalGrade: 80

  7. },

  8. {

  9. name: "Taco",

  10. finalGrade: 100

  11. }

  12. ]

  13. */

</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);">

  1. let finalVal = oldArray.reduce((accumulator, currentValue, currentIndex, array) => {

  2. ...

  3. }), initalValue;

</pre>

image

來(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);">

  1. // our list of ingredients in an array

  2. const ingredients = ['wine', 'tomato', 'onion', 'mushroom']

  3. // a cooking function

  4. const cook = (ingredient) => {

  5. returncooked ${ingredient}``

  6. }

</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);">

  1. const wineReduction = ingredients.reduce((sauce, item) => {

  2. return sauce += cook(item) + ', '

  3. }, '')

  4. // 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);">

  1. const wineReduction = ingredients.reduce((sauce, item) => {

  2. return sauce += cook(item) + ', '

  3. })

  4. // 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);">

  1. const wineReduction = ingredients.reduce((sauce, item, index, array) => {

  2. sauce += cook(item)

  3. if (index < array.length - 1) {

  4. sauce += ', '

  5. }

  6. return sauce

  7. }, '')

  8. // 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);">

  1. const wineReduction = ingredients.reduce((sauce, item, index, array) => {

  2. return (index < array.length - 1) ? sauce +={cook(item)}, ` : sauce += `{cook(item)}``

  3. }, '')

  4. // 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)幫助你們記憶:

視頻地址:https://youtu.be/-YEbBy3Mk

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末喧伞,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子理朋,更是在濱河造成了極大的恐慌絮识,老刑警劉巖,帶你破解...
    沈念sama閱讀 222,807評(píng)論 6 518
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件嗽上,死亡現(xiàn)場(chǎng)離奇詭異,居然都是意外死亡熄攘,警方通過(guò)查閱死者的電腦和手機(jī)兽愤,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 95,284評(píng)論 3 399
  • 文/潘曉璐 我一進(jìn)店門(mén),熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái),“玉大人浅萧,你說(shuō)我怎么就攤上這事逐沙。” “怎么了洼畅?”我有些...
    開(kāi)封第一講書(shū)人閱讀 169,589評(píng)論 0 363
  • 文/不壞的土叔 我叫張陵吩案,是天一觀的道長(zhǎng)。 經(jīng)常有香客問(wèn)我帝簇,道長(zhǎng)徘郭,這世上最難降的妖魔是什么? 我笑而不...
    開(kāi)封第一講書(shū)人閱讀 60,188評(píng)論 1 300
  • 正文 為了忘掉前任丧肴,我火速辦了婚禮残揉,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘芋浮。我一直安慰自己抱环,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 69,185評(píng)論 6 398
  • 文/花漫 我一把揭開(kāi)白布纸巷。 她就那樣靜靜地躺著镇草,像睡著了一般。 火紅的嫁衣襯著肌膚如雪瘤旨。 梳的紋絲不亂的頭發(fā)上陶夜,一...
    開(kāi)封第一講書(shū)人閱讀 52,785評(píng)論 1 314
  • 那天,我揣著相機(jī)與錄音裆站,去河邊找鬼条辟。 笑死,一個(gè)胖子當(dāng)著我的面吹牛宏胯,可吹牛的內(nèi)容都是我干的羽嫡。 我是一名探鬼主播,決...
    沈念sama閱讀 41,220評(píng)論 3 423
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼肩袍,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼杭棵!你這毒婦竟也來(lái)了?” 一聲冷哼從身側(cè)響起氛赐,我...
    開(kāi)封第一講書(shū)人閱讀 40,167評(píng)論 0 277
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤魂爪,失蹤者是張志新(化名)和其女友劉穎,沒(méi)想到半個(gè)月后艰管,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體滓侍,經(jīng)...
    沈念sama閱讀 46,698評(píng)論 1 320
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 38,767評(píng)論 3 343
  • 正文 我和宋清朗相戀三年牲芋,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了撩笆。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片捺球。...
    茶點(diǎn)故事閱讀 40,912評(píng)論 1 353
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖夕冲,靈堂內(nèi)的尸體忽然破棺而出氮兵,到底是詐尸還是另有隱情,我是刑警寧澤歹鱼,帶...
    沈念sama閱讀 36,572評(píng)論 5 351
  • 正文 年R本政府宣布泣栈,位于F島的核電站,受9級(jí)特大地震影響弥姻,放射性物質(zhì)發(fā)生泄漏南片。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 42,254評(píng)論 3 336
  • 文/蒙蒙 一蚁阳、第九天 我趴在偏房一處隱蔽的房頂上張望铃绒。 院中可真熱鬧,春花似錦螺捐、人聲如沸颠悬。這莊子的主人今日做“春日...
    開(kāi)封第一講書(shū)人閱讀 32,746評(píng)論 0 25
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)赔癌。三九已至,卻和暖如春澜沟,著一層夾襖步出監(jiān)牢的瞬間灾票,已是汗流浹背。 一陣腳步聲響...
    開(kāi)封第一講書(shū)人閱讀 33,859評(píng)論 1 274
  • 我被黑心中介騙來(lái)泰國(guó)打工茫虽, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留刊苍,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 49,359評(píng)論 3 379
  • 正文 我出身青樓濒析,卻偏偏與公主長(zhǎng)得像正什,于是被迫代替她去往敵國(guó)和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子号杏,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,922評(píng)論 2 361

推薦閱讀更多精彩內(nèi)容