JavaScript reduce() method
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
.
reduce
(
getSum
)
;
}
Output result:
125
Try it »
Definition and Usage
The reduce() method executes a reducer function (from left to right) on each element of the array, reducing them to a single value.
reduce() can be used as a higher-order function for function composition.
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 | |||||
|---|---|---|---|---|---|
| reduce() | Yes | 9.0 | 3.0 | 4 | 10.5 |
Syntax
array.reduce(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
Calculate the sum of array elements after rounding:
<
button
onclick
=
"
myFunction()
"
Click me
button
<
p
Sum of array elements:
<
span
id
=
"
demo
"
span
p
<
script
var numbers = [15.5, 2.3, 1.1, 4.7]; function getSum(total, num) { return total + Math.round(num); } function myFunction(item) { document.getElementById("demo").innerHTML = numbers.reduce(getSum, 0); }
script
Try it »
JavaScript Array object