doubleyong
管理员
管理员
  • 最后登录2025-12-02
  • 发帖数1198
  • 最爱沙发
  • 喜欢达人
  • 原创写手
  • 社区居民
  • 忠实会员
阅读:5028回复:0

[js]ES6 中reduce()的用法

楼主#
更多 发布于:2020-08-04 16:32
reduce 方法
 
对数组中的所有元素调用指定的回调函数。
该回调函数的返回值为累积结果,并且此返回值在下一次调用该回调函数时作为参数提供。
 
语法
array1.reduce(callbackfn[, initialValue])
 
array1       必需。一个数组对象。
callbackfn 必需。一个接受最多四个参数的函数。
nitialValue 可选。如果指定 initialValue,则它将用作初始值来启动累积
 
返回值
通过最后一次调用回调函数获得的累积结果。
 
异常
当满足下列任一条件时,将引发 TypeError 异常:
callbackfn 参数不是函数对象。
数组不包含元素,且未提供 initialValue。
备注
如果提供了 initialValue,则 reduce 方法会对数组中的每个元素调用一次 callbackfn 函数(按升序索引顺序)。
如果未提供 initialValue,则 reduce 方法会对从第二个元素开始的每个元素调用 callbackfn 函数。
 
 
回调函数语法
回调函数的语法如下所示:
function callbackfn(previousValue, currentValue, currentIndex, array1)

callback:函数中包含四个参数
- previousValue (上一次调用回调返回的值,或者是提供的初始值(initialValue))
- currentValue (数组中当前被处理的元素)
- index (当前元素在数组中的索引)
- array (调用的数组)
 
initialValue (作为第一次调用 callback 的第一个参数。)

常见应用

递归利用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)


处理数据并,累加


function absolute(prev,curr){
       return Math.abs(prev)+Math.abs(curr)
   }
   var arr4 = [-2];
   //不传initVal,观察差别
   var result4 = arr4.reduce(absolute);
   //传initVal,
   var result5 = arr4.reduce(absolute,0);
   console.info('result4',result4) //-2
   console.info('result5',result5) //2

参考 :
https://www.cnblogs.com/lizimeme/p/7743742.html
https://www.cnblogs.com/smallpen/p/10249288.html
知识需要管理,知识需要分享
游客


返回顶部

公众号

公众号