定义和用法
reduceRight() 方法的功能和 reduce() 功能是一样的,不同的是 reduceRight() 从数组的末尾向前将数组中的数组项做累加。
注意: reduce() 对于空数组是不会执行回调函数的。
语法
array.reduceRight(function(total, currentValue, currentIndex, arr), initialValue)
参数
| 参数 | 描述 | ||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|
| function(total,currentValue, index,arr) | 必需。用于执行每个数组元素的函数。 函数参数:
|
||||||||||
| initialValue | 可选。传递给函数的初始值 |
浏览器支持
所有主流浏览器都支持reduceRight()方法。

实例 1
计算数组元素相加后的总和:
<button onclick="myFunction()">点我</button>
<p>数组元素总和: <span id="demo"></span></p>
<script>
var numbers = [65, 44, 12, 4];
function getSum(total, num) {
return total + num;
}
function myFunction(item) {
document.getElementById("demo").innerHTML = numbers.reduceRight(getSum);
}
</script>
输出结果:125
实例 2
从右到左,减去每个数组元素:
<p>点击按钮从右到左,由最后一个元素开始减去每个数组的元素。</p>
<button onclick="myFunction()">点我</button>
<p>计算后的值: <span id="demo"></span></p>
<script>
var numbers = [2, 45, 30, 100];
function getSum(total, num) {
return total - num;
}
function myFunction(item) {
document.getElementById("demo").innerHTML = numbers.reduceRight(getSum);
}
</script>
计算后的值: 23