reduce()方法
定义: reduce()接收一个函数作为累加器, 数组中每个值 (从左到右) 开始缩减, 最终计算为一个值
对于空数组不执行回调函数
语法: array.reduce(function(total, currentValue, currentIndex, arr), initialValue);
total: 必需初始值, 或者计算结束后的返回值
currentValue: 必需当前元素
currentIndex: 可选当前元素的索引
arr: 可选当前元素所属的数组对象
initialValue: 可选传递给函数的初始值;
返回值: 返回计算结果
例 1:
- var numbers = [33, 54, 23, 5];
- function getSum(total, num) {
- return total + num;
- }
- function myFunction(item) {
- document.getElementById("demo").innerhtml = numbers.reduce(getSum);
- }
例 2:
- <button onclick="myFunction()">点我</button>
- <p > 数组元素之和:<span id="demo"></span></p>
- <script>
- var numbers = [12.5, 2.3, 3.3, 33.7];
- function getSum(total, num) {
- return total + Math.round(num);
- }
- function myFunction(item) {
- document.getElementById("demo").innerHTML = numbers.reduce(getSum, 0);
- }
- </script>
来源: https://www.cnblogs.com/insignificant-malt/p/8522976.html