reduce() 方法接收一个函数作为累加器,数组中的每个值(从左到右)开始缩减,最终计算为一个值。
注意: reduce() 对于空数组是不会执行回调函数的。
语法:
array.reduce(function(total, currentValue, currentIndex, arr), initialValue)
参数:
案例:
四舍五入后计算数组元素的总和:
<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>
参考文档:
https://www.runoob.com/jsref/jsref-reduce.html