Filtr tablicy JavaScript
Przykład 1
Zwraca tablicę wszystkich wartości w ages[], które mają 18 lat lub więcej:
const ages = [32, 33, 16, 40];
const result = ages.filter(checkAdult);
function checkAdult(age) {
return age >= 18;
}
Definicja i użycie
Metoda filter()
tworzy nową tablicę wypełnioną elementami, które przechodzą test dostarczony przez funkcję.
Metoda filter()
nie wykonuje funkcji dla pustych elementów.
Metoda filter()
nie zmienia oryginalnej tablicy.
Składnia
array.filter(function(currentValue, index, arr), thisValue)
Parametry
Parameter | Description |
function() | Required. A function to run for each array element. |
currentValue | Required. The value of the current element. |
index | Optional. The index of the current element. |
arr | Optional. The array of the current element. |
thisValue | Optional. Default undefined A value passed to the function as its this value. |
Wartość zwrotu
Rodzaj | Opis |
Tablica |
Zawiera elementy, które przejdą test. Jeśli żaden element nie przejdzie testu, zwraca pustą tablicę. |
Obsługa przeglądarki
filter()
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 |
Przykład 2
Zwróć wartości w ages[], które przekraczają określoną liczbę:
<p><input type="number" id="ageToCheck" value="30"></p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
const ages = [32, 33, 12, 40];
function checkAge(age) {
return age > document.getElementById("ageToCheck").value;
}
function myFunction() {
document.getElementById("demo").innerHTML = ages.filter(checkAge);
}
</script>