- 累加
const arr = [1, 2, 3, 4]
arr.reduce((preV, curV) => preV + curV)
- 累乘
const arr = [1, 2, 3, 4]
arr.reduce((preV, curV) => preV * curV)
- 求数组最大项
const arr = [1, 4, 3 ,5, 2 ,4]
arr.reduce((preV, curV) => Math.max(preV, curV))
Math.max(...arr)
- 计算数组中每个元素出现的次数
const heros = ['敌法师', '虚空假面', '风行者', '冰女', '敌法师', '风行者', '敌法师', '冰女']
function count(allHeros, hero) {
if(hero in allHeros) {
allHeros[hero]++
}
else {
allHeros[hero] = 1
}
return allHeros
}
heros.reduce(count, {})
- 数组去重
const heros = ['敌法师', '虚空假面', '风行者', '冰女', '敌法师', '风行者', '敌法师', '冰女']
function deweight(allHeros, hero) {
if(allHeros.indexOf(hero) === -1) {
allHeros.push(hero)
}
return allHeros
}
heros.reduce(deweight, [])