JavaScript reduceRight() 方法


计算数组元素相加后的总和:

  1. var numbers = [65, 44, 12, 4];
  2. function getSum(total, num) {
  3. return total + num;
  4. }
  5. function myFunction(item) {
  6. document.getElementById("demo").innerHTML = numbers.reduceRight(getSum);
  7. }
运行一下

输出结果:

125

定义和用法

reduceRight() 方法的功能和 reduce() 功能是一样的,不同的是 reduceRight() 从数组的末尾向前将数组中的数组项做累加。

注意: reduce() 对于空数组是不会执行回调函数的。


浏览器支持

表格中的数字表示支持该方法的第一个浏览器版本号。
方法







reduceRight() Yes 9.0 3.0 4 10.5


语法

  1. array.reduce(function(total, currentValue, currentIndex, arr), initialValue)

参数

参数 描述
function(total,currentValue, index,arr) 必需。用于执行每个数组元素的函数。
函数参数:
参数 描述
total 必需。初始值, 或者计算结束后的返回值。
currentValue 必需。当前元素
currentIndex 可选。当前元素的索引
arr 可选。当前元素所属的数组对象。
initialValue 可选。传递给函数的初始值

技术细节

返回值: 返回计算结果
JavaScript 版本: ECMAScript 3

更多实例

实例

从右到左,减去每个数组元素:

  1. <button onclick="myFunction()">点我</button>
  2. <p>计算后的值: <span id="demo"></span></p>
  3. <script>
  4. var numbers = [2, 45, 30, 100];
  5. function getSum(total, num) {
  6. return total - num;
  7. }
  8. function myFunction(item) {
  9. document.getElementById("demo").innerHTML = numbers.reduceRight(getSum);
  10. }
  11. </script>
运行一下