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;});".
The operating environment of this tutorial: Windows 10 system, ECMAScript version 6.0, Dell G3 computer.
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:
##[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!