计算数组元素相加后的总和:
运行一下
- var numbers = [65, 44, 12, 4];
- function getSum(total, num) {
- return total + num;
- }
- function myFunction(item) {
- document.getElementById("demo").innerHTML = numbers.reduce(getSum);
- }
输出结果:
reduce() 方法接收一个函数作为累加器,数组中的每个值(从左到右)开始缩减,最终计算为一个值。
注意: reduce() 对于空数组是不会执行回调函数的。
表格中的数字表示支持该方法的第一个浏览器版本号。
方法
|
|
|
|
|
|
---|---|---|---|---|---|
reduce() | Yes | 9.0 | 3.0 | 4 | 10.5 |
- array.reduce(function(total, currentValue, currentIndex, arr), initialValue)
参数 | 描述 | ||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|
function(total,currentValue, index,arr) |
必需。用于执行每个数组元素的函数。 函数参数:
|
||||||||||
initialValue | 可选。传递给函数的初始值 |
返回值: | 返回计算结果 |
---|---|
JavaScript 版本: | ECMAScript 3 |
四舍五入后计算数组元素的总和:
运行一下
- <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>