JavaScript Array reduce() 方法

定义和用法

reduce() 方法将数组缩减为单个值。

reduce() 方法为数组的每个值(从左到右)执行提供的函数。

函数的返回值存储在累加器中(结果/总计)。

注释:对没有值的数组元素,不执行 reduce() 方法。

注释:reduce() 方法不会改变原始数组。

实例

例子 1

从开始减去数组中的数字:

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

Try it yourself

Example 2

Round all numbers in the array and display the total:

<button onclick="myFunction()">Try it</button>
<p>Sum of numbers in array: <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 yourself

Syntax

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

Parameter values

Parameters Description
function(total, currentValue, index, arr) Required. The function to be run for each element in the array.

Function parameters:

Parameters Description
total Required. initialValue, or the value previously returned by the function.
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 to the function as the initial value.

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 reduce() 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

Tutoriales:JavaScript Array

Tutoriales:Array Const de JavaScript

Tutoriales:Métodos de arrays de JavaScript

Tutoriales:Ordenar arrays de JavaScript

Tutoriales:Iteración de arrays de JavaScript

Manual:Método Array.reduceRight()