在JavaScript中,Array.prototype.reduce
方法是一个非常有用的函数,它允许你将一个数组减少(reduce)为一个单一的值。这个方法对于计算数组中所有元素的总和、求最大值、最小值或者执行更复杂的操作(如对象数组中的属性累加)非常有用。
reduce
方法的基本语法如下:
arr.reduce(callback(accumulator, currentValue, currentIndex, array), initialValue)
参数说明:
callback
:执行数组中每个元素的函数,它接受四个参数:accumulator
(累加器):累加回调的返回值; 它是上一次调用回调时返回的累积值,或者是提供的初始值(initialValue
)。currentValue
:数组中正在处理的当前元素。currentIndex
(可选):数组中正在处理的当前元素的索引。array
(可选):调用reduce
方法的数组。
initialValue
(可选):作为第一次调用callback
函数时的第一个参数的值。
案例:
1、求和
//求和
calculateTotalPrice() {
this.totalPrice = this.snackList.reduce((sum, item) => {
return sum + item.snackPrice;
}, 0);
},
2、求最大值
//求最大值
calculateTotalPrice() {
this.totalPrice = this.snackList.reduce((max, item) => {
return Math.max(max, item.snackPrice);
}, Number.NEGATIVE_INFINITY);
},
3、求最小值
//求最小值
calculateTotalPrice() {
this.totalPrice = this.snackList.reduce((min, item) => {
return Math.min(min, item.snackPrice);
}, Number.POSITIVE_INFINITY);
},