js中reduce函数
时间: 2023-10-13 19:24:49 浏览: 93
在 JavaScript 中,reduce() 是数组中的一个方法,它接收一个回调函数并对数组中的每个元素执行该回调函数,最终返回一个单一的值。
reduce() 方法接收两个参数:
1. 回调函数:这个函数接收四个参数: accumulator (累加器), currentValue (当前值), currentIndex (当前索引)和 array (数组本身)。
2. 初始值(可选):作为回调函数的第一个参数传递给回调函数的初始值。如果没有提供初始值,则使用数组中的第一个元素作为初始值,并从数组的第二个元素开始执行回调函数。
回调函数中的 accumulator 参数是一个累加器,它在每次执行回调函数时都会被更新。第一次执行回调函数时,accumulator 的值等于传递给 reduce() 方法的初始值。在下一次执行回调函数时,accumulator 的值等于上一次回调函数的返回值。
reduce() 方法可以用于对数组中的元素进行求和、求平均值、查找最大值或最小值等操作。下面是一些使用 reduce() 方法的例子:
```javascript
// 求和
const numbers = [1, 2, 3, 4, 5];
const sum = numbers.reduce((accumulator, currentValue) => accumulator + currentValue, 0);
console.log(sum); // 15
// 求平均值
const grades = [80, 90, 70, 85, 95];
const average = grades.reduce((accumulator, currentValue, index, array) => {
accumulator += currentValue;
if (index === array.length - 1) {
return accumulator / array.length;
} else {
return accumulator;
}
}, 0);
console.log(average); // 84
// 查找最大值
const numbers = [10, 20, 5, 30, 15];
const max = numbers.reduce((accumulator, currentValue) => {
if (currentValue > accumulator) {
return currentValue;
} else {
return accumulator;
}
}, numbers[0]);
console.log(max); // 30
```
需要注意的是,reduce() 方法不会修改原始数组。如果需要修改原始数组,可以使用 map() 方法或 forEach() 方法。
阅读全文
相关推荐















