<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>js arr.reduce()</title>
</head>
<body>
<script>
/*参考:https://www.runoob.com/jsref/jsref-reduce.html
1.array.reduce(function(total, currentValue, currentIndex, arr), initialValue)
reduce() 方法接收一个函数作为累加器,数组中的每个值(从左到右)开始缩减,最终计算为一个值。
reduce() 可以作为一个高阶函数,用于函数的组成。
注意: reduce() 对于空数组是不会执行回调函数的。
function(total, currentValue, currentIndex, arr),必需。用于执行每个数组元素的函数。
total,必需。初始值, 或者计算结束后的返回值。
currentValue,必需。当前元素
currentIndex,可选。当前元素的索引
arr,可选。当前元素所属的数组对象。
initialValue,可选。传递给函数的初始值*/
// 1.
function sum1(total, num) {
/*功能:数组元素求和。*/
return total + num;
}
let numbers = [1, 2, 3, 4];
console.log(numbers.reduce(sum1));
// 10
// 2.封装成一个函数。
function sum(arr) {
/*功能:数组求和。*/
return arr.reduce(function (total, currentValue, currentIndex, arr) {
return total + currentValue;
});
}
console.log(sum(numbers)); // 10
// 3.“四舍五入”后,求和。
function sum2(total, num) {
/*功能:数组元素“四舍五入”后,求和。*/
return total + Math.round(num);
}
numbers = [1.5, 2.3, 3.1, 4.7];
console.log(numbers.reduce(sum2, 0));
// 12
console.log(numbers.reduce(sum2, 1));
// 13
</script>
</body>
</html>