reduce
作用:reduce返回累计处理的结果,经常用于求和等。
//基本语法
arr.reduce(function(){
},起始值)
arr.reduce(function(上一次值,当前值){
},初始值)
- 示例1
const arr = [1, 3, 5, 7]
const total = arr.reduce((prev, cur) => {
return prev + cur
})
console.log(total) // 16
- 示例2:存在初始值
const arr = [1, 3, 5, 7]
const total = arr.reduce((prev, cur) => {
return prev + cur
}, 10)
console.log(total) // 26
- 示例3:数组对象,要给初始值
const arr = [
{
name: '张三',
salary: 10000
},
{
name: '李四',
salary: 10000
},
{
name: '王五',
salary: 10000
},
]
const totalSalary = arr.reduce((prev, cur) => {
return prev + cur.salary
}, 0)
console.log(totalSalary) //30000