当前位置:网站首页>Introduction to the reduce() function in JS
Introduction to the reduce() function in JS
2022-07-28 02:48:00 【The tide does not fall】
Definition
reduce() Method to receive a function as an accumulator , Every value in the array ( From left to right ) Start to shrink , The final calculation is a value .
reduce() As a higher-order function , For functions compose.
Be careful : reduce() Callbacks are not performed for empty arrays .
grammar
array.reduce(function(total, currentValue, currentIndex, arr), initialValue)Syntax reference above Rookie League
Usually , The first parameter Use prev ( as follows )
arr.reduce(function(prev,cur,index,arr){
...
}, init);

prev: Last call callbackFn The return value of . On the first call , If an initial value is specified init, Its value is init, Otherwise, the array index is 0 The elements of arr[0].
cur: The element being processed in the array . On the first call , If an initial value is specified init, Its value is array index 0 The elements of arr[0], Otherwise arr[1].
index: The index of the element being processed in the array . If an initial value is specified init, The starting index number is 0, Otherwise from index 1 start .
arr: Array for traversal .
Is it a feeling to see so many parameters reduce Very complicated , I thought so at first , Then repeatedly understand the meaning of the above parameters , I know, usually , The commonly used parameters are only the two parameters that must be selected above prev,cur , Let's take a look at the case
Case study
1. Array sum
Usually , We often use for loop perhaps forEach , Use here reduc It will also be more concise , as follows
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. Find the maximum value of an array item
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) //66Because no initial value was passed in , So at the beginning prev The value of is an array The first one is 1,cur The value of is an array The second item 5, Take the maximum of two values 5 As a function of the next round prev , Take the next item of the array, that is The third one 8 As a function of the next round cur , Continue to the next round of adjustment to compare the size , So again and again , To get the maximum value of the array .
3. Flatten a two-dimensional array
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]The initial value is passed here init Empty array [ ] , So start saying prev The value of is [ ] , cur For the first item of the array [1, 2, 8], Then proceed concat operation
summary
reduce(callback,initiaValue) Two variables are passed in , Callback function (callback) And the initial value (init).
The function has four incoming parameters ,prev and cur,index and array. Prev and cur It's what you have to know .
When no initial value is passed in ,prev It starts with the first element in the array ,cur Is the second element of the array .
But when the initial value is passed (init) after , first prev Will be the initial value init,cur Will be the first element in the array .
arr Represents the original array ;
prev Represents the return value when the callback was last called , Or the initial value init;
cur Represents the array element currently being processed ;
index Represents the index of the array element currently being processed , If provided init value , The index is 0, Otherwise the index is 1;
init Represents the initial value .
If there is any mistake in the article , Please ask questions , I am obliged . You can comment on what you don't understand , I will be one A reply
If the article is helpful to you , I hope you can praise and encourage , We will work together in the future Long journey , The resistance and long
边栏推荐
- Typescript (zero) -- introduction, environment construction, first instance
- Three core issues of concurrent programming (glory Collection Edition)
- Explore flex basis
- Interviewer: what is the factory method mode?
- LETV responded that employees live an immortal life without internal problems and bosses; Apple refuses to store user icloud data in Russia; Dapr 1.8.0 release | geek headlines
- PS simple to use
- Network must know topics
- Design of edit memory path of edit box in Gui
- 第二季度邮件安全报告:邮件攻击暴增4倍,利用知名品牌获取信任
- TypeScript(零) —— 简介、环境搭建、第一个实例
猜你喜欢

入职华为od一个月的感受

1313_pyserial的安装以及文档的生成
![[signal denoising] signal denoising based on Kalman filter with matlab code](/img/9e/9e569c83dc3106570cf7571056867f.png)
[signal denoising] signal denoising based on Kalman filter with matlab code

Use of Day6 functions and modules

关于Sqli-labs单引号不报错的问题
![[elm classification] classification of UCI data sets based on nuclear limit learning machine and limit learning machine, with matlab code](/img/50/f063cec7610015a062e3773d9916cd.png)
[elm classification] classification of UCI data sets based on nuclear limit learning machine and limit learning machine, with matlab code

Interviewer: what is the factory method mode?

【微信小程序开发(六)】绘制音乐播放器环形进度条

Usage of delegate

Center-based 3D Object Detection and Tracking(基于中心的3D目标检测和跟踪 / CenterPoint)论文笔记
随机推荐
2022.7.8 supplement of empty Luna
【信号去噪】基于卡尔曼滤波实现信号去噪附matlab代码
Is the interface that can be seen everywhere in the program really useful? Is it really right?
On the problem that sqli labs single quotation marks do not report errors
mysql: error while loading shared libraries: libtinfo.so. 5 solutions
Common SQL statement query
windbg
Canvas 从入门到劝朋友放弃(图解版)
Lombok prompts variable log error when using JUnit test in idea
MySQL's way to solve deadlock - lock analysis of common SQL statements
mysql 如图所示,现有表a,表b,需求为 通过projectcode关联a、b表,查出address不同的 idcardnum。
Canonical Address
【TA-霜狼_may-《百人计划》】图形3.7 移动端TP(D)R架构
Newline required at end of file but not found.
Retainface use error: modulenotfounderror: no module named'rcnn.cyton.bbox'
[TA frost wolf \u may hundred people plan] Figure 3.5 early-z and z-prepass
【自我成长网站收集】
What problems should be avoided when using BigDecimal type? (glory Collection Edition)
How do you use the jar package sent by others (how to use the jar package sent by others)
Welcome to CSDN markdown editor Assad