Zmniejsz tablicę JavaScript()
Przykłady
Odejmij wszystkie liczby w tablicy:
const numbers = [175, 50, 25];
document.getElementById("demo").innerHTML
= numbers.reduce(myFunc);
function myFunc(total, num) {
return total - num;
}
Zaokrąglij wszystkie liczby i wyświetl sumę:
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);
}
Definicja i użycie
Metoda reduce()
wykonuje funkcję reduktora dla elementu tablicy.
Metoda reduce()
zwraca pojedynczą wartość: skumulowany wynik funkcji.
Metoda reduce()
nie wykonuje funkcji dla pustych elementów tablicy.
Metoda reduce()
nie zmienia oryginalnej tablicy.
Zobacz też:
Składnia
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. |
Wartość zwrotu
Skumulowany wynik ostatniego wywołania funkcji zwrotnej. |
Obsługa przeglądarki
reduce()
to funkcja ECMAScript5 (ES5).
ES5 (JavaScript 2009) w pełni obsługiwany we wszystkich przeglądarkach:
Chrome | IE | Edge | Firefox | Safari | Opera |
Yes | 9-11 | Yes | Yes | Yes | Yes |