好程序員web前端教程分享js reduce方法使用教程,reduce() 方法接收一個函數作爲累加器,數組中的每個值(從左到右)開始縮減,最終計算爲一個值。
reduce() 可以作爲一個高階函數,用於函數的 compose。
語法:
array.reduce(function(total, currentValue, currentIndex, arr), initialValue)
參數:
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>
兼容性:
不支持ie9以下