1.语法
array.reduce(function(total, currentValue, currentIndex, arr), initialValue)
reduce最多可以接收两个参数,第一个参数为必须,是一个函数,此函数实现累加器的作用。第二个参数非必须,是计算的初始值。
如果数组为空,则不会调用reduce中传入的函数。
1.1作为reduce入参的累加器函数,它最多可以有四个入参:
1.total
: 计算后的和
2.currentValu
:当前项
3.currentIndex
:当前项在数组中的索引
4.arr
:当前数组
其中total
和currentValue
这两个入参必须存在,另外两个可选。
1.2 关于非必须的初始值
虽然可以只传入累加器函数,不传入语法中initialValue位置的初始值参数,但最好还是传入。否则,当数组为空数组[]的时候,浏览器会报错Reduce of empty array with no initial value,如图:
加入初始值后:
2.示例(使用了es6的箭头函数)
普通数组,求和:
let numberArray = [1,2,3,4,5];
let numberSum = numberArray.reduce((sum, curr) => sum + curr);
对象数组,计算学生的年龄和:
let studentsArray = [
{
name: '张飞',
age: 20
},
{
name: '赵云',
age: 10
}
];
let ageSum = studentsArray.reduce((ageSum, currStudent) => {
return ageSum + currentStudent.age;
},0)