JavaScript的reduce() 方法使用

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

猜你喜欢

转载自blog.csdn.net/qq_34661750/article/details/114082896
今日推荐