js中reduce() 方法使用

reduce

reduce()方法接收一个函数作为累加器,reduce 为数组中的每一个元素依次执行回调函数,接受四个参数:初始值(上次回调得返回值),当前元素值,当前索引,原数组 。

参数 function(total,currentValue,currentIndex,arr);

// total  必需。初始值,或者计算结束后得返回值。
// currentValue  必需。当前元素。
// currentIndex  可选。当前元素得索引
// arr 可选。当前元素所属的数组对象。


// initialValue 可选,传递给函数的初始值。

应用

var orderDetail=[
{Id:1,name:"产品A",total:50 },
{Id:2,name:"产品B",total:20 },
{Id:3,name:"产品C",total:30 }
];

var sum=orderDetail.reduce(function(total,currentValue,currentIndex,arr){
     return total=total+currentValue.total;
},0)

console.log(sum); // 100
 

以上回调被调用3次 。

callbak

total

currentValue

currentIndex

arr

 return

第一次

0

{Id:1,name:"产品A",total:50}

0

[{Id:1,name:"产品A",total:50 }, {Id:2,name:"产品B",total:20 },
{Id:3,name:"产品C",total:30 }]

 50

第二次

50

 {Id:2,name:"产品B",total:20}

1

 

[{Id:1,name:"产品A",total:50 }, {Id:2,name:"产品B",total:20 },
{Id:3,name:"产品C",total:30 }]

 70

第三次

70

 {Id:3,name:"产品C",total:30}

2

 

[{Id:1,name:"产品A",total:50 }, {Id:2,name:"产品B",total:20 },
{Id:3,name:"产品C",total:30 }]

 100

原文地址:https://www.cnblogs.com/xiaofeixiaa/p/13262918.html