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