Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

JavaScript reduceRight() method

JavaScript reduceRight() method

Array Object Reference JavaScript Array object

Example

Calculate the sum of all array elements:

var

numbers

=

[

65

,

44

,

12

,

4

]

;

function

getSum

(

total

,

num

)

{

return

total

num

;

}

function

myFunction

(

item

)

{

document

.

getElementById

(

"

demo

"

)

.

innerHTML

=

numbers

.

reduceRight

(

getSum

)

;

}

Output result:

125

Try it »


Definition and Usage

The reduceRight() method has the same functionality as reduce() , except that reduceRight() accumulates the array items from the end to the beginning.

Note: reduce() does not execute the callback function for empty arrays.


Browser support

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

Method
reduceRight() Yes 9.0 3.0 4 10.5

Syntax


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

Parameters

Parameters Description
function(total,currentValue, index,arr) Required. The function to execute on each array element.
 函数参数:       
Parameter Description   total Required.Initial value, or the return value after the calculation is complete.   currentValue Required. The current element   currentIndex Optional. The index of the current element   arr Optional. The array object to which the current element belongs. | Parameter | Description | *total* | Required. The *initial value*, or the return value after computation. | *currentValue* | Required. The current element | *currentIndex* | Optional. The index of the current element | *arr* | Optional. The array object to which the current element belongs. | | Parameter | Description | | *total* | Required. The *initial value*, or the return value after computation. | | *currentValue* | Required. The current element | | *currentIndex* | Optional. The index of the current element | | *arr* | Optional. The array object to which the current element belongs. | | *initialValue* | Optional. The initial value passed to the function |

Technical Details

Return value: Returns the computed result
JavaScript version: ECMAScript 3

More examples

Example

From right to left, subtract each array element:

<

button

onclick

=

"

myFunction()

"

Click me

button

<

p

Computed value:

<

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 »


Array Object Reference JavaScript Array object