javascript
JavaScript - reduce用法详解
介紹reduce
reduce() 方法接收一個(gè)函數(shù)作為累加器,reduce 為數(shù)組中的每一個(gè)元素依次執(zhí)行回調(diào)函數(shù),不包括數(shù)組中被刪除或從未被賦值的元素,接受四個(gè)參數(shù):初始值(上一次回調(diào)的返回值),當(dāng)前元素值,當(dāng)前索引,原數(shù)組?
語法:arr.reduce(callback,[initialValue])
| 1 2 3 4 5 6 7 | callback:函數(shù)中包含四個(gè)參數(shù) - previousValue (上一次調(diào)用回調(diào)返回的值,或者是提供的初始值(initialValue)) - currentValue (數(shù)組中當(dāng)前被處理的元素) - index (當(dāng)前元素在數(shù)組中的索引) - array (調(diào)用的數(shù)組) ? initialValue (作為第一次調(diào)用 callback 的第一個(gè)參數(shù)。) |
應(yīng)用
const arr = [1, 2, 3, 4, 5] const sum = arr.reduce((pre, item) => {return pre + item }, 0) console.log(sum) // 15以上回調(diào)被調(diào)用5次,每次的參數(shù)詳見下表
| 第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 |
?
1.使用reduce方法可以完成多維度的數(shù)據(jù)疊加
例如:計(jì)算總成績,且學(xué)科的占比不同
const scores = [{subject: 'math',score: 88},{subject: 'chinese',score: 95},{subject: 'english',score: 80}];const dis = {math: 0.5,chinese: 0.3,english: 0.2}const sum = scores.reduce((pre,item) => {return pre + item.score * dis[item.subject]},0)console.log(sum) // 88.5?
2.遞歸利用reduce處理tree樹形
var data = [{id: 1,name: "辦公管理",pid: 0,children: [{id: 2,name: "請假申請",pid: 1,children: [{ id: 4, name: "請假記錄", pid: 2 },],},{ id: 3, name: "出差申請", pid: 1 },]},{id: 5,name: "系統(tǒng)設(shè)置",pid: 0,children: [{id: 6,name: "權(quán)限管理",pid: 5,children: [{ id: 7, name: "用戶角色", pid: 6 },{ id: 8, name: "菜單設(shè)置", pid: 6 },]}, ]},];const arr = data.reduce(function(pre,item){const callee = arguments.callee //將運(yùn)行函數(shù)賦值給一個(gè)變量備用pre.push(item)//判斷當(dāng)前參數(shù)中是否存在children,有則遞歸處理if(item.children && item.children.length > 0) item.children.reduce(callee,pre); return pre;},[]).map((item) => {item.children = []return item})console.log(arr)?
3.還可以利用reduce來計(jì)算一個(gè)字符串中每個(gè)字母出現(xiàn)次數(shù)
const str = 'jshdjsihh';const obj = str.split('').reduce((pre,item) => {pre[item] ? pre[item] ++ : pre[item] = 1return pre},{})console.log(obj) // {j: 2, s: 2, h: 3, d: 1, i: 1}?
參考鏈接:
數(shù)組reduce方法的高級技巧
創(chuàng)作挑戰(zhàn)賽新人創(chuàng)作獎(jiǎng)勵(lì)來咯,堅(jiān)持創(chuàng)作打卡瓜分現(xiàn)金大獎(jiǎng)總結(jié)
以上是生活随笔為你收集整理的JavaScript - reduce用法详解的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 用云服务器建网站的优势是什么
- 下一篇: JS报错-Uncaught TypeEr