JavaScript - reduce用法详解

介绍reduce

reduce() 方法接收一个函数作为累加器,reduce 为数组中的每一个元素依次执行回调函数,不包括数组中被删除或从未被赋值的元素,接受四个参数:初始值(上一次回调的返回值),当前元素值,当前索引,原数组 

语法:arr.reduce(callback,[initialValue])

1

2

3

4

5

6

7

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次,每次的参数详见下表

callbackpreviousValuecurrentValueindexarrayreturn value
第1次010[1, 2, 3, 4, 5]1
第2次121[1, 2, 3, 4, 5]3
第3次332[1, 2, 3, 4, 5]6
第4次643[1, 2, 3, 4, 5]10
第5次1054[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}

 

参考链接:

数组reduce方法的高级技巧

  • 2
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值