JavaScript Array reduction()
Příklady
Odečtěte všechna čísla v poli:
const numbers = [175, 50, 25];
document.getElementById("demo").innerHTML
= numbers.reduce(myFunc);
function myFunc(total, num) {
return total - num;
}
Zaokrouhlete všechna čísla a zobrazte součet:
const numbers = [15.5, 2.3, 1.1, 4.7];
document.getElementById("demo").innerHTML = numbers.reduce(getSum, 0);
function getSum(total, num) {
return total + Math.round(num);
}
Definice a použití
Metoda reduce()
provádí redukční funkci pro prvek pole.
Metoda reduce()
vrací jedinou hodnotu: akumulovaný výsledek funkce.
Metoda reduce()
neprovádí funkci pro prázdné prvky pole.
Metoda reduce()
nemění původní pole.
Viz také:
Syntax
array.reduce(function(total, currentValue, currentIndex, arr), initialValue)
Parametry
Parameter | Description | ||||||||
function() | Required. A function to be run for each element in the array. |
||||||||
Reducer function parameters:
| |||||||||
initialValue | Optional. A value to be passed to the function as the initial value. |
Návratová hodnota
Souhrnný výsledek z posledního volání funkce zpětného volání. |
Podpora prohlížeče
reduce()
je funkce ECMAScript5 (ES5).
ES5 (JavaScript 2009) plně podporován ve všech prohlížečích:
Chrome | IE | Edge | Firefox | Safari | Opera |
Yes | 9-11 | Yes | Yes | Yes | Yes |