The reduce() method receives a function as an accumulator, and each value in the array (from left to right) is initially reduced and finally computed to a value.
Note: reduce() will not execute the callback function for empty arrays.
grammar:
array.reduce(function(total, currentValue, currentIndex, arr), initialValue)
Parameters:
Case:
Computes the sum of array elements after rounding:
<button onclick="myFunction()">点我</button>
<p>数组元素之和: <span id="demo"></span></p>
<script>
var numbers = [15.5, 2.3, 1.1, 4.7];
function getSum(total, num) {
return total + Math.round(num);
}
function myFunction(item) {
document.getElementById("demo").innerHTML = numbers.reduce(getSum, 0);
}
</script>
Reference document:
https://www.runoob.com/jsref/jsref-reduce.html