好程序員web前端教程分享js reduce方法使用教程,reduce() 方法接收一個函數做爲累加器,數組中的每一個值(從左到右)開始縮減,最終計算爲一個值。前端
reduce() 能夠做爲一個高階函數,用於函數的 compose。程序員
語法:web
array.reduce(function(total, currentValue, currentIndex, arr), initialValue)數組
參數:函數
total 必需。初始值, 或者計算結束後的返回值。spa
currentValue 必需。當前元素對象
currentIndex 可選。當前元素的索引教程
arr 可選。當前元素所屬的數組對象。索引
initialValue 可選。傳遞給函數的初始值ip
實例:
<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如下