当我们在进行一些求和操作的时候就会使用数组的reduce方法。
let total = 0;
let array = [1, 2, 3, 4, 5];
total = array.reduce((prev, next) => {
return prev + next;
}, 0);
console.log(total);
例如我们数组里面是几个商品的价格,怎么去求商品总价呢
开始我是这么处理的,代码如下
let totalPrice = 0;
let goodsList = [
{
price: 20
},
{
price: 30
},
{
price: 50
}
];
totalPrice = goodsList.reduce((prev, next) => {
return prev.price + next.price;
});
上面代码看着没有任何毛病,但是,结果就会出现NaN。因为prev是前几项的和,结果是个数字怎么能有price属性,结果就为undefined。所以总和就是NaN。
应该改为:
let totalPrice = 0;
let goodsList = [
{
price: 20
},
{
price: 30
},
{
price: 50
}
];
// 默认传如一个参数0,prev的第一项就是0,每次加上下一次的价格即可
totalPrice = goodsList.reduce((prev, next) => {
return prev + next.price;
}, 0);