reduceRight()
方法通过从右到左对数组的两个值(右到左)执行 回调函数,将 数组 归约到单个值。
示例
let numbers = [1, 2, 3, 4];
// function that adds last two values of the numbers array
function sum_reducer(accumulator, currentValue) {
return accumulator + currentValue;
}
// returns a single value after reducing the numbers array
let sum = numbers.reduceRight(sum_reducer);
console.log(sum);
// Output: 10
reduceRight() 语法
reduceRight()
方法的语法是
arr.reduceRight(callback(accumulator, currentValue), initialValue)
这里,arr 是一个数组。
reduceRight() 参数
reduceRight()
方法可以接受 **两个** 参数
- callback - 对每个数组元素执行的函数。它接收
-
- accumulator - 它累积回调的返回值。如果提供了
initialValue
,则对于第一次调用,它就是initialValue
。
- accumulator - 它累积回调的返回值。如果提供了
-
- currentValue - 从数组中传递的当前元素。
- initialValue (可选) - 一个将在第一次调用时传递给
callback()
的值。如果不提供,最后一个元素将作为第一次调用的 accumulator,callback()
不会对其执行。
注意: 在没有 initialValue 的情况下对空数组调用 reduceRight()
将抛出 TypeError
。
reduceRight() 返回值
- 返回归约数组后产生的值。
注意事项:
reduceRight()
从右到左为每个值执行给定的函数。reduceRight()
不会改变原始数组。- 提供
initialValue
几乎总是更安全。
示例 1:使用 reduceRight() 方法
let numbers = [1, 2, 3, 4, 5, 6];
// function that adds last two values of the numbers array
function sum_reducer(accumulator, currentValue) {
return accumulator + currentValue;
}
// returns a single value after reducing the numbers array
let sum = numbers.reduceRight(sum_reducer);
console.log(sum);
输出
21
在上面的示例中,我们使用 reduceRight()
方法将 numbers 数组转换为单个值。
我们定义了一个名为 sum_reducer()
的函数,它接受两个参数并返回它们的和。
由于我们没有传递 initialValue,最后一个元素 **6** 是 accumulator,**5** 是 currentValue。
reduceRight()
方法执行回调 sum_reducer()
,并将 6+5 的结果之和(即新的 accumulator)与新的 currentValue **4** 相加。
此过程将一直持续到达到 numbers 的第一个值为止。
示例 2:在 reduceRight() 方法中传递 initialValue
let expense = [50, 300, 20, 100, 1800];
// function that returns sum of two values
function add(accumulator, currentValue) {
return accumulator + currentValue;
}
// adds 0 with last value of expense (i.e 1800)
// and executes the callback add()
let result = expense.reduceRight(add, 0);
console.log(result);
输出
2270
在上面的示例中,我们传递了 initialValue- **0**,它充当 accumulator。
numbers.reduceRight(add, 0)
首先将 **0** 与 expense 数组的最后一个值即 **1800** 相加。然后它执行 add()
并将数组的其余元素(从右到左)相加。
该方法最终返回单个值总和,即 **2270**。
另请阅读