Home  >  Article  >  Web Front-end  >  How to use reduce to sum in es6

How to use reduce to sum in es6

WBOY
WBOYOriginal
2022-04-25 15:56:272646browse

In es6, the reduce() method can traverse the array, perform some calculation on the two items before and after the array, then return its value, and continue the calculation without changing the original array, and return the final result of the calculation. For sum calculation, the syntax is "arr.reduce(function(a,b){sum=a b;});".

How to use reduce to sum in es6

The operating environment of this tutorial: Windows 10 system, ECMAScript version 6.0, Dell G3 computer.

es6 How to use reduce to sum

Reduce can traverse the array, perform some calculation on the two items before and after the array, and then return its value and continue the calculation without changing the original array and return to the calculation. The final result; if no initial value is given, the traversal starts from the second item of the array.

The reduce() method receives a function as an accumulator, and each value in the array (from left to right) starts to be reduced and finally calculated to a value.

arr.reduce(function(p,c){sum=p+c;});

The example is as follows:

var arr = [1, 2, 3], sum = 0;
arr.reduce(function(pre,curr) {
sum=pre+curr;
return sum;
});
console.log(sum);

Output result:

How to use reduce to sum in es6

##[Related recommendations:

javascript video tutorial,webfrontend

The above is the detailed content of How to use reduce to sum in es6. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn