介紹reduce
reduce() 方法接收一個函數作爲累加器,reduce 爲數組中的每一個元素依次執行回調函數,不包括數組中被刪除或從未被賦值的元素,接受四個參數:初始值(上一次回調的返回值),當前元素值,當前索引,原數組
一、語法
arr.reduce(callback,[initialValue])
二、應用
const arr = [1, 2, 3, 4, 5]
const sum = arr.reduce((pre, item) => {
return pre + item
}, 0)
console.log(sum) // 15
以上回調被調用5次,每次的參數詳見下表
使用reduce方法可以完成多維度的數據疊加。
例如:計算總成績,且學科的佔比不同
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
遞歸利用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: "系統設置",
pid: 0,
children: [{
id: 6,
name: "權限管理",
pid: 5,
children: [
{ id: 7, name: "用戶角色", pid: 6 },
{ id: 8, name: "菜單設置", pid: 6 },
]
}, ]
},
];
const arr = data.reduce(function(pre,item){
const callee = arguments.callee //將運行函數賦值給一個變量備用
pre.push(item)
if(item.children && item.children.length > 0) item.children.reduce(callee,pre); //判斷當前參數中是否存在children,有則遞歸處理
return pre;
},[]).map((item) => {
item.children = []
return item
})
console.log(arr)
還可以利用reduce來計算一個字符串中每個字母出現次數
在這裏插入代碼片
const str = 'jshdjsihh';
const obj = str.split('').reduce((pre,item) => {
pre[item] ? pre[item] ++ : pre[item] = 1
return pre
},{})
console.log(obj) // {j: 2, s: 2, h: 3, d: 1, i: 1}
如何知道一串字符串中每個字母出現的次數?
可以運用reduce來解決這個問題。
如下代碼,我在reduce的第二個參數裏面初始了回調函數第一個參數的類型和值,將字符串轉化爲數組,那麼迭代的結果將是一個對象,對象的每一項key值就是字符串的字母。運行感受一下吧。
var arrString = 'abcdaabc';
arrString.split('').reduce(function(res, cur) {
res[cur] ? res[cur] ++ : res[cur] = 1
return res;
}, {})
由於可以通過第二參數設置疊加結果的類型初始值,因此這個時候reduce就不再僅僅只是做一個加法了,我們可以靈活的運用它來進行各種各樣的類型轉換,比如將數組按照一定規則轉換爲對象,也可以將一種形式的數組轉換爲另一種形式的數組,大家可以動手去嘗試一樣。
[1, 2].reduce(function(res, cur) {
res.push(cur + 1);
return res;
}, [])
這種特性使得reduce在實際開發中大有可爲!但是需要注意點,在ie9一下的瀏覽器中,並不支持該方法 !
三、後記
喜歡的小夥伴可以關注我哦,相互交流,相互學習