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"