JavaScript - 数组 .reduceRight() 方法
在 JavaScript 中,Array.reduceRight() 方法对累加器和数组中的每个元素(从右到左)应用一个函数,将其缩减为单个值。
此方法不会对空数组元素执行 Reducer 函数。此外,它也不会修改原始数组。
注意 - 如果当前数组为空或不包含任何初始值,此方法将抛出 'TypeError' 异常。
reduce() 和 reduceRight() 之间的区别
reduce() 和 reduceRight() 方法几乎相似,但它们之间略有不同。 reduce() 方法从左到右迭代数组,而 reduceRight() 方法从右到左迭代数组。
语法
以下是 JavaScript Array.reduceRight() 方法的语法 -
reduceRight(callbackFn(accumulator, currentValue, currentIndex, array), initialValue)
参数
-
callbackFn - 这是对数组中每个元素执行的函数。此函数接受四个参数:
- accumulator − 这是函数的初始值,即先前返回的值。
- currentValue − 这是数组中当前正在处理的元素。如果指定了 initialValue,则其值将是最后一个元素;如果没有指定,则其值将是倒数第二个元素。
- currentIndex(可选)- 这是当前正在处理的元素在数组中的索引。
- array(可选)- 这是调用 reduce() 方法的数组。
- initialValue(可选)- 首次调用回调函数时,accumulator 参数初始化的值。
返回值
此方法返回对数组进行 Reduce 后的结果。
示例
示例 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

