介紹reduce
reduce() 方法接收一個函數作為累加器
,reduce 為數組中的每一個元素依次執行回調函數,不包括數組中被刪除或從未被賦值的元素,接受四個參數:初始值(上一次回調的返回值),當前元素值,當前索引,原數組
語法:arr.reduce(callback,[initialValue])
callback:函數中包含四個參數 - previousValue (上一次調用回調返回的值,或者是提供的初始值(initialValue)) - currentValue (數組中當前被處理的元素) - index (當前元素在數組中的索引) - array (調用的數組) initialValue (作為第一次調用 callback 的第一個參數。)
應用
const arr = [1, 2, 3, 4, 5] const sum = arr.reduce((pre, item) => { return pre + item }, 0) console.log(sum) // 15
以上回調被調用5次,每次的參數詳見下表
callback | previousValue | currentValue | index | array | return value |
---|---|---|---|---|---|
第1次 | 0 | 1 | 0 | [1, 2, 3, 4, 5] | 1 |
第2次 | 1 | 2 | 1 | [1, 2, 3, 4, 5] | 3 |
第3次 | 3 | 3 | 2 | [1, 2, 3, 4, 5] | 6 |
第4次 | 6 | 4 | 3 | [1, 2, 3, 4, 5] | 10 |
第5次 | 10 | 5 | 4 | [1, 2, 3, 4, 5] | 15 |
使用reduce方法可以完成多維度的數據疊加。
例如:計算總成績,且學科的占比不同
1 const scores = [ 2 { 3 subject: 'math', 4 score: 88 5 }, 6 { 7 subject: 'chinese', 8 score: 95 9 }, 10 { 11 subject: 'english', 12 score: 80 13 } 14 ]; 15 const dis = { 16 math: 0.5, 17 chinese: 0.3, 18 english: 0.2 19 } 20 const sum = scores.reduce((pre,item) => { 21 return pre + item.score * dis[item.subject] 22 },0) 23 console.log(sum) // 88.5
遞歸利用reduce處理tree樹形
1 var data = [{ 2 id: 1, 3 name: "辦公管理", 4 pid: 0, 5 children: [{ 6 id: 2, 7 name: "請假申請", 8 pid: 1, 9 children: [ 10 { id: 4, name: "請假記錄", pid: 2 }, 11 ], 12 }, 13 { id: 3, name: "出差申請", pid: 1 }, 14 ] 15 }, 16 { 17 id: 5, 18 name: "系統設置", 19 pid: 0, 20 children: [{ 21 id: 6, 22 name: "權限管理", 23 pid: 5, 24 children: [ 25 { id: 7, name: "用戶角色", pid: 6 }, 26 { id: 8, name: "菜單設置", pid: 6 }, 27 ] 28 }, ] 29 }, 30 ]; 31 const arr = data.reduce(function(pre,item){ 32 const callee = arguments.callee //將運行函數賦值給一個變量備用 33 pre.push(item) 34 if(item.children && item.children.length > 0) item.children.reduce(callee,pre); //判斷當前參數中是否存在children,有則遞歸處理 35 return pre; 36 },[]).map((item) => { 37 item.children = [] 38 return item 39 }) 40 console.log(arr)
還可以利用reduce來計算一個字符串中每個字母出現次數
1 const str = 'jshdjsihh'; 2 const obj = str.split('').reduce((pre,item) => { 3 pre[item] ? pre[item] ++ : pre[item] = 1 4 return pre 5 },{}) 6 console.log(obj) // {j: 2, s: 2, h: 3, d: 1, i: 1}
參考 👏😬