js reduce函式詳解
阿新 • • 發佈:2021-01-03
Javascript reduce()方法經常用於陣列求和
1.方法原型
reduce(function(preValue, currentValue, currentIndex, arr), initialValue)
function()定義一個函式說明求值的具體實現,必須
preValue:累積值,必須
currentValue: 當前元素,必須
currentIndex: 當前陣列索引,可選
arr:陣列物件,可選
initialValue:初始值,可選
2.reduce實現原理
當不傳入初始值時程式碼:
const arr = [15, 2, 1, 4]
const totalValue = arr.reduce(function(preValue,currentValue){
console.log(preValue)
console.log(currentValue)
console.log("------------")
return preValue + currentValue
})
結果:
當傳入初始值時程式碼:
const arr = [15, 2, 1, 4]
const totalValue = arr.reduce(function(preValue,currentValue){
console.log(preValue)
console.log(currentValue)
console.log( "------------")
return preValue + currentValue
},0)
結果:
當傳入初始值時,相當於向陣列開頭新增一個元素,陣列變成[0,15,2,1,4]
3.當陣列中元素為簡單數值時,初始值可有可無,但當陣列元素為物件時,初始值就起到了很大的作用
程式碼:
const goods1 = {name: "goods1", price: 100, count: 1}
const goods2 = {name: "goods1", price: 200, count: 2}
const goods3 = {name: "goods1", price: 300, count: 3}
const goodsList = [goods1, goods2, goods3];
const totalPrice = goodsList.reduce(function(preValue, currentGoods){
console.log(preValue)
console.log(currentGoods)
return preValue.price * preValue.count + currentGoods.price * currentGoods.count
})
如上程式碼,計算商品價格總和,當不傳入初始值時結果:
第一次列印preValue是goods1物件,currentValue是goods2物件
計算後得到500,return給下一次計算
第二次呼叫時preValue是500這個數值,不是物件,所以preValue時沒有price和count屬性的,導致運算出錯
顯然第一次呼叫preValue是goodsList[0],是一個物件,隨後的幾次呼叫preValue都是計算得到的值
解決辦法:加上初始值0
const goods1 = {name: "goods1", price: 100, count: 1}
const goods2 = {name: "goods1", price: 200, count: 2}
const goods3 = {name: "goods1", price: 300, count: 3}
const goodsList = [goods1, goods2, goods3];
const totalPrice = goodsList.reduce(function(preValue, currentGoods){
console.log(preValue)
console.log(currentGoods)
return preValue + currentGoods.price * currentGoods.count
},0)
結果:
原因:加上初始值後陣列變成[0,goods1物件,goods2物件,goods3物件]
這樣第一次呼叫preValue就是一個數值,而不會是一個物件了