介绍reduce
reduce() 方法接收一个函数作为累加器
,reduce 为数组中的每一个元素依次执行回调函数,不包括数组中被删除或从未被赋值的元素,接受四个参数:初始值(上一次回调的返回值),当前元素值,当前索引,原数组
语法:arr.reduce(callback,[initialValue])
1 2 3 4 5 6 7 |
|
应用
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 |
1.使用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
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: "系统设置",
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)
//判断当前参数中是否存在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来计算一个字符串中每个字母出现次数
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}
参考链接: