在 JavaScript 中,Array.reduceRight() 方法对累加器和数组中的每个元素(从右到左)应用一个函数,以将其减少为单个值。
此方法不会为空数组元素执行 reducer 函数。除此之外,它不会修改原始数组。
注 -如果当前数组为空或不包含任何 initialValue,此方法将引发 'TypeError' 异常。
reduce() 和 reduceRight() 之间的区别
reduce() 和 reduceRight() 方法几乎相似,但它们之间略有不同。reduce() 方法从左到右迭代数组,而 reduceRight() 方法从右到左迭代数组。
语法
以下是 JavaScript Array.reduceRight() 方法的语法 -
reduceRight(callbackFn(accumulator, currentValue, currentIndex, array), initialValue)
参数
- callbackFn −这是对数组中的每个元素执行的函数。此函数采用四个参数:
- accumulator -这是 initialValue 或函数之前返回的值。
- currentValue - 当前值 -这是数组中正在处理的当前元素。如果指定了 initialValue,则其值将是最后一个元素,否则其值将是倒数第二个元素。
- currentIndex(可选)−这是数组中正在处理的当前元素的索引。
- array(可选)−这是调用 reduce() 方法的数组。
- initialValue(可选)-首次调用回调函数时 accumulator 参数初始化为的值。
返回值
此方法返回单个值,该值是缩减数组后的结果。
例子
示例 1
在下面的示例中,reduceRight() 从最后一个元素开始,使用累加器的初始值,从末尾到开头将数组元素相加。
<html>
<body>
<script>
const numbers = [10, 20, 30, 40, 50];
const sum = numbers.reduceRight((accumulator, currentValue) => accumulator + currentValue, 0);
document.write(sum);
</script>
</body>
</html>
输出
150
示例 2
在此示例中,reduceRight() 方法以数组的最后一个元素 (50) 和空数组作为累加器开始。它从右到左迭代,将每个元素推送到累加器。
<html>
<body>
<script>
const numbers = [10, 20, 30, 40, 50];
const reversedNumbers = numbers.reduceRight((accumulator, currentValue) => {
accumulator.push(currentValue);
return accumulator;
}, []);
document.write(reversedNumbers);
</script>
</body>
</html>
输出
50,40,30,20,10
示例 3
在这里,reduceRight() 方法从最后一个嵌套数组 ([5, 6]) 和一个空数组作为累加器开始。它从右到左迭代,将每个数组连接到累加器。
<html>
<body>
<script>
const arrays = [[1, 2], [3, 4], [5, 6]];
const flattenedArray = arrays.reduceRight((accumulator, currentValue) => accumulator.concat(currentValue), []);
document.write(flattenedArray);
</script>
</body>
</html>
输出
5,6,3,4,1,2
示例 4
如果当前数组不包含任何元素(没有可用的初始值),reduce() 方法将抛出 “TypeError” 异常。
<html>
<body>
<script>
const numbers = [];
try {
numbers.reduce((accumulator, currentValue) => accumulator * currentValue);
} catch (error) {
document.write(error);
}
</script>
</body>
</html>
输出
TypeError: Reduce of empty array with no initial value