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

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

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

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

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

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

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

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

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"

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

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

最新文章

  1. Python 学习第十六天 html 前端内容总结
  2. BZOJ1055: [HAOI2008]玩具取名
  3. 打造自己的视频会议系统 GGMeeting(附送源码)
  4. 【读书笔记《Android游戏编程之从零开始》】6.Android 游戏开发常用的系统控件(TabHost、ListView)
  5. Visual Studio无法添加断点
  6. rpm方式安装gcc缺少依赖项的解决方法
  7. RabbitMQ笔记
  8. 【USACO 3.1.4】形成的区域
  9. js 中null 和 undifined
  10. ASP.NET Core MVC 模型绑定用法及原理
  11. C语言获取系统时间的函数
  12. Docker基础知识介绍
  13. Android WebView 加载超长 JS 数据
  14. GCD HDU - 1695 (欧拉 + 容斥)
  15. Java-把日期字符串转换成另一种格式的日期字符串
  16. Hadoop集群(三) Hbase搭建
  17. php faker 库填充数据
  18. EOJ 262 润清的烦恼
  19. linux 添加samba账户
  20. android assets与 assets与res/raw 的相同、不同点

热门文章

  1. 电路维修(双端队列 &amp; 最短路)
  2. linux 内核源代码情景分析——地址映射的全过程
  3. WPF实现统计图
  4. virt-v2v命令将ESXI 虚机迁移到OpenStack中
  5. Spring Cloud Alibaba 使用Feign进行服务消费
  6. 好好的 Tair 排行榜不用,非得自己写?20 行代码实现高性能排行榜
  7. VSCode 微信小程序 开发环境配置 详细教程
  8. 快速排序--洛谷卡TLE后最终我还是选择了三向切割
  9. String你会用吗?
  10. inux 下配置网卡的别名即网卡子IP的配置 转