返回

【JS】208-图解 Map、Reduce 和 Filter 数组方法

发布时间:2022-12-03 02:06:56 295

 

英文:Una Kravets 译文:熊贤仁

map、reduce 和 filter 是三个非常实用的 JavaScript 数组方法,赋予了开发者四两拨千斤的能力。我们直接进入正题,看看如何使用(并记住)这些超级好用的方法!

Array.map()

Array.map() 根据传递的转换函数,更新给定数组中的每个值,并返回一个相同长度的新数组。它接受一个回调函数作为参数,用以执行转换过程。

  1. let newArray = oldArray.map((value, index, array) => {
  2. ...
  3. });

一个帮助记住 map 的方法:Morph Array Piece-by-Piece(逐个改变数组)

你可以使用 map 代替 for-each 循环,来遍历并对每个值应用转换函数。这个方法适用于当你想更新数组的同时保留原始值。它不会潜在地删除任何值(filter 方法会),也不会计算出一个新的输出(就像 reduce 那样)。map 允许你逐个改变数组。一起来看一个例子:

  1. [1, 4, 6, 14, 32, 78].map(val => val * 10)
  2. // the result is: [10, 40, 60, 140, 320, 780]

上面的例子中,我们使用一个初始数组([1, 4, 6, 14, 32, 78]),映射每个值到它自己的十倍(val * 10)。结果是一个新数组,初始数组的每个值被这个等式转换:[10, 40, 60, 140, 320, 780]。

【JS】208-图解 Map、Reduce 和 Filter 数组方法_数组方法

Array.filter()

当我们想要过滤数组的值到另一个数组,新数组中的每个值都通过一个特定检查,Array.filter() 这个快捷实用的方法就派上用场了。

类似搜索过滤器,filter 基于传递的参数来过滤出值。

举个例子,假定有个数字数组,想要过滤出大于 10 的值,可以这样写:

  1. [1, 4, 6, 14, 32, 78].filter(val => val > 10)
  2. // the result is: [14, 32, 78]

但是 filter 方法,只返回真值。因此如果所有值都执行指定的检查的话,结果的长度会小于等于原始数组。

把 filter 想象成一个漏斗。部分混合物会从中穿过进入结果,而另一部分则会被留下并抛弃。

【JS】208-图解 Map、Reduce 和 Filter 数组方法_数组_02

假设宠物训练学校有一个四只狗的小班,学校里的所有狗都会经过各种挑战,然后参加一个分级期末考试。我们用一个对象数组来表示这些狗狗:

  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. ]

如果狗狗们的期末考试成绩高于 70 分,它们会获得一个精美的证书;反之,它们就要去重修。为了知道证书打印的数量,要写一个方法来返回通过考试的狗狗。不必写循环来遍历数组的每个对象,我们可以用 filter 简化代码!

  1. const passingDogs = students.filter((student) => {
  2. return student.finalGrade >= 70
  3. })
  4.  
  5. /*
  6. passingDogs = [
  7. {
  8. name: "Boops",
  9. finalGrade: 80
  10. },
  11. {
  12. name: "Taco",
  13. finalGrade: 100
  14. }
  15. ]
  16. */

你也看到了,Boops 和 Taco 是好狗狗(其实所有狗都很不错),它们取得了通过课程的成就证书!利用箭头函数的隐式返回特性,一行代码就能实现。因为只有一个参数,所以可以删掉箭头函数的括号:

  1. const passingDogs = students.filter(student => student.finalGrade >= 70)
  2.  
  3. /*
  4. passingDogs = [
  5. {
  6. name: "Boops",
  7. finalGrade: 80
  8. },
  9. {
  10. name: "Taco",
  11. finalGrade: 100
  12. }
  13. ]
  14. */

Array.reduce()

reduce() 方法接受一个数组作为输入值并返回一个值。这点挺有趣的。reduce 接受一个回调函数,回调函数参数包括一个累计器(数组每一段的累加值,它会像雪球一样增长),当前值,和索引。reduce 也接受一个初始值作为第二个参数:

  1. let finalVal = oldArray.reduce((accumulator, currentValue, currentIndex, array) => {
  2. ...
  3. }), initalValue;

【JS】208-图解 Map、Reduce 和 Filter 数组方法_数组_03

来写一个炒菜函数和一个作料清单:

  1. // our list of ingredients in an array
  2. const ingredients = ['wine', 'tomato', 'onion', 'mushroom']
  3.  
  4. // a cooking function
  5. const cook = (ingredient) => {
  6. return `cooked ${ingredient}`
  7. }

如果我们想要把这些作料做成一个调味汁(开玩笑的),用 reduce() 来归约!

  1. const wineReduction = ingredients.reduce((sauce, item) => {
  2. return sauce += cook(item) + ', '
  3. }, '')
  4.  
  5. // wineReduction = "cooked wine, cooked tomato, cooked onion, cooked mushroom, "

初始值(这个例子中的 '')很重要,它决定了第一个作料能够进行烹饪。这里输出的结果不太靠谱,自己炒菜时要当心。下面的例子就是我要说到的情况:

  1. const wineReduction = ingredients.reduce((sauce, item) => {
  2. return sauce += cook(item) + ', '
  3. })
  4.  
  5. // wineReduction = "winecooked tomato, cooked onion, cooked mushroom, "

最后,确保新字符串的末尾没有额外的空白,我们可以传递索引和数组来执行转换:

  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.  
  9. // wineReduction = "cooked wine, cooked tomato, cooked onion, cooked mushroom"

可以用三目操作符、模板字符串和隐式返回,写的更简洁(一行搞定!):

  1. const wineReduction = ingredients.reduce((sauce, item, index, array) => {
  2. return (index < array.length - 1) ? sauce += `${cook(item)}, ` : sauce += `${cook(item)}`
  3. }, '')
  4.  
  5. // wineReduction = "cooked wine, cooked tomato, cooked onion, cooked mushroom"

记住这个方法的简单办法就是回想你怎么做调味汁:把多个作料归约到单个。

和我一起唱起来!

我想要用一首歌来结束这篇博文,给数组方法写了一个小调,来帮助你们记忆:

视频地址:https://youtu.be/-YEbBy3Mk

 

【JS】208-图解 Map、Reduce 和 Filter 数组方法_数组_04

 

特别声明:以上内容(图片及文字)均为互联网收集或者用户上传发布,本站仅提供信息存储服务!如有侵权或有涉及法律问题请联系我们。
举报
评论区(0)
按点赞数排序
用户头像
精选文章
thumb 中国研究员首次曝光美国国安局顶级后门—“方程式组织”
thumb 俄乌线上战争,网络攻击弥漫着数字硝烟
thumb 从网络安全角度了解俄罗斯入侵乌克兰的相关事件时间线