数组中reduce
方法的使用
-
定义:reduce()方法接受一个函数作为累加器,数组中的每个值(从左到右)。
-
语法:
array.reduce(function(total, currentValue, currentIndex, arr), initialValue)
total
:计算结束后的返回值 (必须)
currentValue
:当前元素 (必须)
currentIndex
:当前元素的索引(可选)
arr
:当前元素所属的数组对象(可选)
initialValue
:传递给函数的初始值(可选) -
我们直接上函数
total() {
return this.bookList.reduce((total, item)=> {
total += item.price * item.num
return total
}, 0)
},
reduce函数中执行了item的价格和数量相乘的操作然后累加,最终返回total值是各种商品的总价,由于reduce方法返回的是个纯函数,所以我们需要用变量接收一下。最后我们的函数返回出最终的结果。