JavaScript Array filter()
Příklad 1
Vrátí pole všech hodnot ve věku[], které jsou starší 18 let:
const ages = [32, 33, 16, 40];
const result = ages.filter(checkAdult);
function checkAdult(age) {
return age >= 18;
}
Definice a použití
Metoda filter()
vytvoří nové pole naplněné prvky, které projdou testem poskytovaným funkcí.
Metoda filter()
neprovádí funkci pro prázdné prvky.
Metoda filter()
nemění původní pole.
Syntax
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. |
Návratová hodnota
Typ | Popis |
Pole |
Obsahující prvky, které projdou testem. Pokud testem neprojdou žádné prvky, vrátí prázdné pole. |
Podpora prohlížeče
filter()
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 |
Příklad 2
Vraťte hodnoty ve věkových skupinách[], které přesahují určité číslo:
<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>