当前位置:网站首页>JS中的reduce()函数介绍
JS中的reduce()函数介绍
2022-07-28 01:38:00 【潮汐未见潮落】
定义
reduce() 方法接收一个函数作为累加器,数组中的每个值(从左到右)开始缩减,最终计算为一个值。
reduce() 可以作为一个高阶函数,用于函数的 compose。
注意: reduce() 对于空数组是不会执行回调函数的。
语法
array.reduce(function(total, currentValue, currentIndex, arr), initialValue)上面的语法参考 菜鸟联盟
通常情况下,第一个参数 使用 prev (如下)
arr.reduce(function(prev,cur,index,arr){
...
}, init);

prev:上一次调用 callbackFn 时的返回值。在第一次调用时,若指定了初始值 init,其值则为 init,否则为数组索引为 0 的元素 arr[0]。
cur:数组中正在处理的元素。在第一次调用时,若指定了初始值 init,其值则为数组索引为 0 的元素 arr[0],否则为 arr[1]。
index:数组中正在处理的元素的索引。若指定了初始值 init,则起始索引号为 0,否则从索引 1 起始。
arr:用于遍历的数组。
看到这么多参数是不是感觉 reduce 很复杂,一开始我也是这么认为的,然后反复理解上面那些参数的含义,知道了通常情况下,常用的参数只有前面必选的两个参数 prev,cur ,下面我们来看案例
案例
1.数组求和
通常情况下,对数组求和我们常使用 for 循环 或者 forEach ,这里使用 reduc 也会比较简洁,如下
var arr = [1,5,8,10,15,66,65,25,48,55]
// forEach
var eachSum = 0;
arr.forEach( item =>{
eachSum += item
})
console.log(eachSum); //298var arr = [1,5,8,10,15,66,65,25,48,55]
// reduce
var sum = arr.reduce(function(prev,cur){
return prev+cur;
});
console.log(sum); //2982. 求数组项最大值
var arr = [1,5,8,10,15,66,65,25,48,55]
var max = arr.reduce(function (prev, cur) {
return Math.max(prev,cur);
});
console.log(max) //66由于未传入初始值,所以开始时 prev 的值为数组第一项 1,cur 的值为数组第二项 5,取两值最大值 5 作为下一轮函数的 prev ,取数组下一项也就是 第三项 8作为下一轮函数的 cur ,继续进入下一轮回调比较大小,如此反复,从而得到数组最大值。
3.扁平一个二维数组
var arr = [[1, 2, 8], [3, 4, 9], [5, 6, 10]];
var res = arr.reduce((prev, cur) => prev.concat(cur), []);
console.log(res) // [1,2,8,3,4,9,5,6,10]这里传入初始值 init 为空数组 [ ] ,所以开始说 prev 的值为 [ ] , cur 为数组第一项 [1, 2, 8],然后进行 concat 操作
总结
reduce(callback,initiaValue)会传入两个变量,回调函数(callback)和初始值(init)。
函数有四个传入参数,prev和cur,index和array。 Prev和 cur 是你必须要了解的。
当没有传入初始值时,prev是从数组中第一个元素开始的,cur 是数组第二个元素。
但是当传入初始值(init)后,第一个 prev 将是初始值 init,cur 将是数组中的第一个元素。
arr 表示原数组;
prev 表示上一次调用回调时的返回值,或者初始值 init;
cur 表示当前正在处理的数组元素;
index 表示当前正在处理的数组元素的索引,若提供 init 值,则索引为0,否则索引为1;
init 表示初始值。
文章如有错误,恳请大家提出问题,本人不胜感激 。 不懂的地方可以评论,我都会一 一回复
文章对大家有帮助的话,希望大家能动手点赞鼓励,大家未来一起努力 长路漫漫,道阻且长
边栏推荐
- Alipay applet authorization / obtaining user information
- Email security report in the second quarter: email attacks have soared fourfold, and well-known brands have been used to gain trust
- First knowledge of C language -- operators and keywords, define, pointer
- Should programmers choose outsourcing companies
- 【信号去噪】基于卡尔曼滤波实现信号去噪附matlab代码
- Deep Residual Learning for Image Recognition浅读与实现
- [advanced ROS chapter] Lecture 10 gadf integrated simulation process and examples based on gazebo
- MySQL is shown in the figure. The existing tables a and B need to be associated with a and B tables through projectcode to find idcardnum with different addresses.
- Pytorch optimizer settings
- [TA frost wolf \u may - hundred people plan] Figure 3.7 TP (d) r architecture of mobile terminal
猜你喜欢

第三章 队列

【TA-霜狼_may-《百人计划》】图形3.5 Early-z 和 Z-prepass
![[Yugong series] use of tabby integrated terminal in July 2022](/img/df/bf01fc77ae019200d1bf57be783cb9.png)
[Yugong series] use of tabby integrated terminal in July 2022

新基建助力智能化道路交通领域的转型发展

Wechat campus maintenance and repair applet graduation design finished product of applet completion work (4) opening report
![[leetcode] 13. linked list cycle · circular linked list](/img/58/c8796bb5ed96d09325b8f2fa6a709e.png)
[leetcode] 13. linked list cycle · circular linked list

Canvas 从入门到劝朋友放弃(图解版)

First knowledge of C language -- operators and keywords, define, pointer

AWS elastic three swordsman

IO流:节点流和处理流详细归纳。
随机推荐
Which users are suitable for applying for rapidssl certificate
Leetcode judge whether palindrome number
Smart contract security -- selfdestroy attack
Alipay applet authorization / obtaining user information
【HCIP】BGP 特性
Share an esp32 relay
树的孩子兄弟表示法
【OpenGL】GLES20.glClear
In practical work, how do I use postman for interface testing?
Sqlserver problem solving: replication components are not installed on this server. Please run SQL Server Setup again and select the option to install replication components
Use try-with-resources or close this
Soft test - database (2) relational model
What problems should be avoided when using BigDecimal type? (glory Collection Edition)
First knowledge of C language -- operators and keywords, define, pointer
Please, don't use the command line to configure MySQL master-slave replication. Isn't it fragrant to deploy with urlos interface?
【自我成长网站收集】
Three core issues of concurrent programming (glory Collection Edition)
First knowledge of C language -- structure, branch and loop statements
Unity saves pictures to albums and rights management
MySQL's way to solve deadlock - lock analysis of common SQL statements