JavaScript Array reduce() 方法
- Página anterior push()
- Próxima página reduceRight()
- Voltar à página anterior Manual de Referência JavaScript Array
定义和用法
reduce()
该方法将数组缩减为单个值。
reduce()
该方法为数组的每个值(从左到右)执行提供的函数。
函数的返回值存储在累加器中(结果/总计)。
注释:对于没有值的数组元素,不执行 reduce()
方法。
注释:reduce()
该方法不会改变原始数组。
实例
例子 1
从开头开始减去数组中的数字:
var numbers = [175, 50, 25]; document.getElementById("demo").innerHTML = numbers.reduce(myFunc); function myFunc(total, num) {}} return total - num; }
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>
Syntax
array.reduce(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:
|
||||||||||
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 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
Tutorial:JavaScript Array
Tutorial:Array Const do JavaScript
Tutorial:Métodos de array do JavaScript
Tutorial:Ordenação de arrays do JavaScript
Tutorial:Iteração de arrays do JavaScript
Manual:Método Array.reduceRight()
- Página anterior push()
- Próxima página reduceRight()
- Voltar à página anterior Manual de Referência JavaScript Array