JavaScript Array reduceRight() Methode

Definition und Verwendung

reduceRight() Die Methode reduziert das Array auf einen einzigen Wert.

reduceRight() Die Methode führt die angegebene Funktion für jeden Wert des Arrays (von rechts nach links) aus.

Der Rückgabewert der Funktion wird im Akkumulator gespeichert (Ergebnis/Gesamtsumme).

Anmerkung:Führen Sie keine Aktion durch für Array-Elemente ohne Wert reduceRight() Methode.

Beispiel

Beispiel 1

Ziehen Sie die Zahlen aus dem Array ab, beginnend mit dem Ende:

var numbers = [175, 50, 25];
document.getElementById("demo").innerHTML = numbers.reduceRight(myFunc);
function myFunc(total, num) {
  return total - num;
}

Try it yourself

Example 2

Subtract numbers from right to left and display the total:

<button onclick="myFunction()">Try it</button>
<p>Sum of numbers in array: <span id="demo"></span></p>
<script>
var numbers = [2, 45, 30, 100];
function getSum(total, num) {
  return total - num;
}
function myFunction(item) {
  document.getElementById("demo").innerHTML = numbers.reduceRight(getSum);
}
</script>

Try it yourself

Syntax

array.reduceRight(function(total, currentValue, currentIndex, arr), initialValue)

Parameter values

Parameters Description
function(total, currentValue, index, arr) Required. A function that is run for each element in the array.

Function parameters:

Parameters Description
total Required. initialValue, or the value returned by the function previously.
currentValue Required. The value of the current element.
index Optional. The array index of the current element.
arr Optional. The array object to which the current element belongs.
initialValue Optional. The value passed as the initial value to the function.

Technical details

Return value: Returns the cumulative result of the last call to the callback function.
JavaScript version: ECMAScript 5

Browser support

The numbers in the table indicate the first browser version that fully supports this method.

All browsers fully support this method. reduceRight() Method:

Chrome IE Edge Firefox Safari Opera
Chrome 3 IE 9 Edge 12 Firefox 3 Safari 5 Opera 10.5
June 2009 September 2010 July 2015 January 2009 June 2010 March 2010

Related pages

Tutorial:JavaScript-Array

Tutorial:JavaScript-Array-Const

Tutorial:JavaScript-Array-Methode

Tutorial:JavaScript-Array-Sortierung

Tutorial:JavaScript-Array-Iteration

Handbuch:Array.reduce() Methode