首页 > 编程知识 正文

数组reduce方法,es6常用方法

时间:2023-05-05 04:28:58 阅读:109043 作者:1456

reduce方法

为数组中的所有元素调用指定的回调函数。

回调函数的返回值是累积的结果,并在下次调用回调函数时作为参数提供。

语法

array1.Reduce(callbackfn (,initialValue] ) ) )

需要阵列1。 数组对象。

需要呼叫反馈。 最多接受四个参数的函数。

nitialValue是可选的。 如果指定initialValue,它将用作开始累积的初始值。

返回值

上次调用回调函数获得的累积结果。

异常

如果满足以下条件之一,将发生TypeError异常:

callbackfn参数不是函数对象。

数组不包含元素,并且不提供initialValue。

备注

如果指定了initialValue,则reduce方法将按升序索引顺序为数组中的每个元素调用一次callbackfn函数。

如果未指定initialValue,reduce方法将为从第二个元素开始的每个元素调用callbackfn函数。

回调函数语法

回调函数的语法如下:

functioncallbackfn (previous value,currentValue,currentIndex,array1) )。

callback:函数包含四个参数

- previousValue (上次调用回调返回的值或指定的初始值(initialValue ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) )。

- currentValue (数组中当前正在处理的元素) ) ) ) ) ) ) ) ) ) ) ) ) )。

- index (数组中当前元素的索引)

- array (调用数组) ) ) ) )。

initial value (作为第一次调用callback的第一个参数。 )

一般APP情况

利用递归处理树

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 }、

]

(,) ]

(,

];

constarr=data.reduce (function (pre,item ) {

const callee=arguments.callee //将执行函数指派给替代变量

pre.push(item )

item.children item.children.length0) item.children.Reduce(callee,pre ); //判断当前参数中是否存在children,如果存在,则递归处理

return pre;

(,) )、 map((item )={

item.children=[]

返回项目

() )

console.log(arr )处理并相加数据

函数absolute (prev,curr ) {

returnmath.ABS(prev ) math.ABS (curr ) )。

}

var arr4=[-2];

不传递initVal,观察差异

varresult4=arr4. reduce (absolute );

如果传递initVal,则、

varresult5=arr4. reduce (absolute,0 );

console.info('result4',result4)//-2

console.info('result5',result5)//2

参考:

33559 www.cn blogs.com/lizi meme/p/7743742.html

33559 www.cn blogs.com/small pen/p/10249288.html

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。