js中reduce用法详解
介绍reduce
reduce() 方法接收一个函数作为累加器
,reduce 为数组中的每一个元素依次执行回调函数,不包括数组中被删除或从未被赋值的元素,接受四个参数:初始值(上一次回调的返回值),当前元素值,当前索引,原数组
语法:arr.reduce(callback,[initialValue])
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次,每次的参数详见下表
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 |
使用reduce方法可以完成多维度的数据叠加。
例如:计算总成绩,且学科的占比不同
1 const scores = [
2 {
3 subject: 'math',
4 score: 88
5 },
6 {
7 subject: 'chinese',
8 score: 95
9 },
10 {
11 subject: 'english',
12 score: 80
13 }
14 ];
15 const dis = {
16 math: 0.5,
17 chinese: 0.3,
18 english: 0.2
19 }
20 const sum = scores.reduce((pre,item) => {
21 return pre + item.score * dis[item.subject]
22 },0)
23 console.log(sum) // 88.5
递归利用reduce处理tree树形
1 var data = [{
2 id: 1,
3 name: "办公管理",
4 pid: 0,
5 children: [{
6 id: 2,
7 name: "请假申请",
8 pid: 1,
9 children: [
10 { id: 4, name: "请假记录", pid: 2 },
11 ],
12 },
13 { id: 3, name: "出差申请", pid: 1 },
14 ]
15 },
16 {
17 id: 5,
18 name: "系统设置",
19 pid: 0,
20 children: [{
21 id: 6,
22 name: "权限管理",
23 pid: 5,
24 children: [
25 { id: 7, name: "用户角色", pid: 6 },
26 { id: 8, name: "菜单设置", pid: 6 },
27 ]
28 }, ]
29 },
30 ];
31 const arr = data.reduce(function(pre,item){
32 const callee = arguments.callee //将运行函数赋值给一个变量备用
33 pre.push(item)
34 if(item.children && item.children.length > 0) item.children.reduce(callee,pre); //判断当前参数中是否存在children,有则递归处理
35 return pre;
36 },[]).map((item) => {
37 item.children = []
38 return item
39 })
40 console.log(arr)
还可以利用reduce来计算一个字符串中每个字母出现次数
1 const str = 'jshdjsihh';
2 const obj = str.split('').reduce((pre,item) => {
3 pre[item] ? pre[item] ++ : pre[item] = 1
4 return pre
5 },{})
6 console.log(obj) // {j: 2, s: 2, h: 3, d: 1, i: 1}
参考
js中reduce用法详解的更多相关文章
- AngularJS select中ngOptions用法详解
AngularJS select中ngOptions用法详解 一.用法 ngOption针对不同类型的数据源有不同的用法,主要体现在数组和对象上. 数组: label for value in a ...
- C++中的STL中map用法详解(转)
原文地址: https://www.cnblogs.com/fnlingnzb-learner/p/5833051.html C++中的STL中map用法详解 Map是STL的一个关联容器,它提供 ...
- JS中this关键字详解
本文主要解释在JS里面this关键字的指向问题(在浏览器环境下). 阅读此文章,还需要心平气和的阅读完,相信一定会有所收获,我也会不定期的发布,分享一些文章,共同学习 首先,必须搞清楚在JS里面,函数 ...
- JS 中 this 关键字详解
本文主要解释在JS里面this关键字的指向问题(在浏览器环境下). 首先,必须搞清楚在JS里面,函数的几种调用方式: 普通函数调用 作为方法来调用 作为构造函数来调用 使用apply/call方法来调 ...
- C++中const用法详解
本文主要内容来自CSDN论坛: http://bbs.csdn.net/topics/310007610 我做了下面几点补充. 补充: 1. 用const声明全局变量时, 该变量仅在本文件内可见, 类 ...
- js 闭包的用法详解
一.闭包 实现可重用的局部变量,且保护其不受污染的机制. 外层函数包裹受保护的变量和内层函数. 内层函数专门负责操作外层函数的局部变量. 将内层函数返回到外层函数外部,反复调用. 二.作用域 子函数会 ...
- JS中navigator对象详解
<code class="language-html"><!doctype html> <html> <head> <meta ...
- AngularJS中transclude用法详解
这篇文章主要介绍了AngularJS中transclude用法,详细分析了transclude的具体功能.使用技巧与相关注意事项,需要的朋友可以参考下 本文实例讲述了AngularJS中transcl ...
- Bom和Dom编程以及js中prototype的详解
一.Bom编程: 1.事件练习: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "h ...
随机推荐
- OAuth 2.0 了解了,OAuth 2.1 呢?
OAuth 2.0 OAuth 2.0 是工业级标准授权协议. OAuth 2.0 聚焦于客户端开发者便利性,为网页应用程序.桌面客户端.手机.客厅设备提供特定的授权流程. RFC6749 OAuth ...
- 手机改 user模式为debug模式
logcat 是Android中一个命令行工具,可用于监控手机应用程序的log信息.网上相关的教学很多,这里只想把自己折腾 2 部手机(一个是三星S4 I9500 港水,Android 5.01,一个 ...
- python-内置函数-callable,chr,ord,bytes,随机验证码生成
s="老男人" bytes(s,encoding="utf-8") 随机验证码的实现方法: 大写字母: li = [] for i in range(6): t ...
- 在Visual Studio 中使用git——文件管理-上(四)
在Visual Studio 中使用git--什么是Git(一) 在Visual Studio 中使用git--给Visual Studio安装 git插件(二) 在Visual Studio 中使用 ...
- XAMPP修改Apache默认网站目录htdocs的详解
XAMPP(Apache+MySQL+PHP+PERL)是一个功能强大的建 XAMPP 软件站集成环境包,大量站长在使用.正确安装好XAMPP后,默认是必须将php程序放到xampp\htdocs文件 ...
- [论文阅读笔记] Fast Network Embedding Enhancement via High Order Proximity Approximati
[论文阅读笔记] Fast Network Embedding Enhancement via High Order Proximity Approximation 本文结构 解决问题 主要贡献 主要 ...
- 图扑软件正式加入腾讯智维生态发展计划,智能 IDC 开启数字经济新征程
4 月 23 日,主题为<智汇科技,维新至善>的腾讯数据中心智维技术研讨会在深圳胜利召开,发布了腾讯智维 2.0 技术体系,深度揭秘了智维 2.0 新产品战略和技术规划.图扑软件(High ...
- 【开源技术分享】无需流媒体服务,让浏览器直接播放rtsp/rtmp的神器:EasyMedia
不同于市面上其他需要各种转发到流媒体服务的中间件来说,EasyMedia不需要依赖任何nginx-rtmp,srs,zlmediakit等等第三方流媒体服务,只需要你有rtsp或者rtmp等等协议的视 ...
- SpringBoot整合shiro系列-SpingBoot是如何将shiroFilter注册到servlet容器中的
一.先从配置类入手,主要是@Bean了一个ShiroFilterFactoryBean: @Data @Configuration @Slf4j @EnableConfigurationPropert ...
- 列表 元组 sort
列表 增append insert extend 迭代增加删 remove delete pop clear改 li[索引]="被修改的内容":切片"" 列表 ...