1. 程式人生 > 實用技巧 >js中reduce() 方法使用

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 結果
第一次 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