Array reduceRight()
reduceRight()方法通过执行reducer函数将给定的数组元素缩减为单个值。 reducer()函数应用于累加器,并从右到左减少所有元素。
语法
array.reduceRight(callback(accumulator,currentValue,currentIndex,array),initialValue)
参数
callback:它是对每个数组元素执行的回调函数。它具有以下参数:
accumulator::它通过回调函数累加initialValue或以前返回的值。
currentValue::它保存正在处理的当前数组元素。
currentIndex:。它是可选的。它保存着当前值的索引,正在处理中。
array::它是可选的。这是元素所属的源数组。
initialValue::这是一个可选参数,将其提供的值用作回调函数的初始调用的累加器。
返回
它将减少单个值作为输出。
注意事项:
当我们第一次调用回调函数时,accumulator和currentValue可以是两个值之一。
当我们在函数中提供initialValue时,累加器将保存initialValue的值,而currentValue将保存数组的最后一个元素。
如果未提供initialValue,则累加器将保存最后一个数组元素,而currentValue将保存倒数第二个数组元素。
当存在没有initialValue的空数组时,它将引发称为 TypeError 的错误。
当它是一个没有initialValue的元素的数组或一个带有initialValue的空数组时,该元素将被返回而无需调用回调函数。
JavaScript数组reduceRight()方法示例
让我们看一些示例以更好地理解:
Example1
这是Array reduceRight()方法的简单实现。
<html>
<head> <h5> JavaScript Array Methods </h5> </head>
<body>
<script>
var arr=[21,2,1,4];
var calc=arr.reduceRight(function(x,y){
return (x+y);
});
document.write(" The sum of the elements is: " +calc);
</script>
</body>
</html>
输出:
但是,在上面的示例中,还不清楚reduceRight()方法是从右到左还是从右到左工作。
Example2
这里是一个实现,显示了reduceRight()方法的工作方向。
<html>
<head> <h5> JavaScript Array Methods </h5> </head>
<body>
<script>
var arr=['t','p','i','r','c','s','a','v','a','j'];
var res=arr.reduceRight(function(right, left){
return (right+left);
});
document.write(" Output is: " +res);
</script>
</body>
</html>
输出:
因此,从上面的输出中可以清楚地知道reduceRight()从右到左起作用。
尽管reduceRight()和reduce()方法都将数组元素缩小为一个价值,它们之间是有区别的。 reduce()方法从左索引位置到右索引减少数组元素。另一方面,reduceRight()方法将数组元素从右索引位置向左减少。
让我们看一下下面的实现以更好地理解。
示例
<html>
<head> <h5> JavaScript Array Methods </h5> </head>
<body>
<script>
var arr=['t','p','i','r','c','s','a','v','a','j'];
var res1=arr.reduceRight(function(pos1, pos2){
return (pos1+pos2);
});
var res2=arr.reduce(function(pos1, pos2){
return (pos1+pos2);
});
document.write(" The reduceRight() method output is: " +res1+"<br>");
document.write("<br> The reduce() method output is: "+res2+ "<br>");
document.write("<br> <center>The above outputs shows that both method works in different manners<center>");
</script>
</body>
</html>
输出:
我们可以实现更多示例来深入了解该方法的工作。