当前位置:网站首页>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 表示初始值。
文章如有错误,恳请大家提出问题,本人不胜感激 。 不懂的地方可以评论,我都会一 一回复
文章对大家有帮助的话,希望大家能动手点赞鼓励,大家未来一起努力 长路漫漫,道阻且长
边栏推荐
- Important arrangements - the follow-up live broadcast of dx12 engine development course will be held at station B
- Get the difference data of two sets
- Canonical Address
- 2022.7.8 supplement of empty Luna
- Achievements in science and Technology (XXVIII)
- 基于FPGA的64位8级流水线加法器
- [advanced ROS] Lecture 9 robot model motion based on rviz and arbotix control
- 新基建助力智能化道路交通领域的转型发展
- Digital empowerment and innovation in the future: hese eredi appears at the 5th Digital China Construction Summit
- 【HCIP】路由策略、策略路由
猜你喜欢

Notes for the fourth time of first knowing C language

POC simulation attack weapon - Introduction to nucleus (I)

关于Sqli-labs单引号不报错的问题

Use try-with-resources or close this

When iPhone copies photos to the computer, the device connection often fails and the transmission is interrupted. Here's the way
![[Yugong series] use of tabby integrated terminal in July 2022](/img/df/bf01fc77ae019200d1bf57be783cb9.png)
[Yugong series] use of tabby integrated terminal in July 2022

retainface使用报错:ModuleNotFoundError: No module named 'rcnn.cython.bbox'

【TA-霜狼_may-《百人计划》】图形3.7 移动端TP(D)R架构

【自我成长网站收集】

How MySQL uses indexes (glory Collection Edition)
随机推荐
[advanced ROS] Lecture 9 robot model motion based on rviz and arbotix control
AWS elastic three swordsman
入职华为od一个月的感受
Red hat official announced the new president and CEO! Paul Cormier, a key figure in transformation, is "retiring"
Alipay applet authorization / obtaining user information
【HCIP】BGP 特性
Unity saves pictures to albums and rights management
Lombok prompts variable log error when using JUnit test in idea
Wechat campus bathroom reservation applet graduation design finished product (2) applet function
In practical work, how do I use postman for interface testing?
Design of edit memory path of edit box in Gui
First knowledge of C language -- operators and keywords, define, pointer
Newline required at end of file but not found.
Learn this trick and never be afraid to let the code collapse by mistake
Typescript (zero) -- introduction, environment construction, first instance
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
From prediction to decision-making, Chapter 9 Yunji datacanvas launched the ylearn causal learning open source project
Common SQL statement query
What can you say to comfort your girlfriend or daughter-in-law
Is the interface that can be seen everywhere in the program really useful? Is it really right?