WPS js中reduce用法
时间: 2023-05-27 15:01:49 浏览: 109
reduce() 是一个数组方法,它用于通过一个函数(callback)在每个元素上递归调用来累加数组中所有项,返回一个累加结果。
语法:
array.reduce(callback[, initialValue]);
参数:
callback: 用于处理每个元素的回调函数,它接收4个参数:
- accumulator:上一次回调函数的结果,或者是传递给reduce()方法的初始值。
- currentValue:当前元素的值。
- currentIndex:当前元素的索引。
- array:调用reduce()方法的数组。
initialValue: 可选的,传递给回调函数的初始值。
示例:
假设有如下数组:
```js
var arr = [1, 2, 3, 4, 5];
```
1. 求和
使用 reduce() 方法可以方便地对数组求和。
```js
var sum = arr.reduce(function(accumulator, currentValue) {
return accumulator + currentValue;
}, 0);
console.log(sum); // 15
```
2. 求最大值
使用 reduce() 方法可以方便地对数组求最大值。
```js
var max = arr.reduce(function(accumulator, currentValue) {
return Math.max(accumulator, currentValue);
}, arr[0]);
console.log(max); // 5
```
3. 求平均值
使用 reduce() 方法可以方便地对数组求平均值。
```js
var avg = arr.reduce(function(accumulator, currentValue, index, array) {
accumulator += currentValue;
if (index === array.length - 1) {
return accumulator / array.length;
}
else {
return accumulator;
}
}, 0);
console.log(avg); // 3
```