JavaScript Array find()
Příklad 1
Najděte hodnotu prvního prvku s hodnotou vyšší než 18:
const ages = [3, 10, 18, 20];
function checkAge(age) {
return age > 18;
}
function myFunction() {
document.getElementById("demo").innerHTML = ages.find(checkAge);
}
Definice a použití
Metoda find()
vrací hodnotu prvního prvku, který projde testem.
Metoda find()
vykonává funkci pro každý prvek pole.
Pokud nejsou nalezeny žádné prvky, metoda find()
se přeladí .undefined
Metoda find()
neprovádí funkci pro prázdné prvky.
Metoda find()
nemění původní pole.
Syntax
array.find(function(currentValue, index, arr),thisValue)
Parametry
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 |
Hodnota |
Hodnota prvního prvku, který prošel testem. Jinak se vrací undefined . |
Podpora prohlížeče
find()
je funkce ECMAScript6 (ES6).
ES6 (JavaScript 2015) je podporován ve všech moderních prohlížečích:
Chrome | Edge | Firefox | Safari | Opera |
Yes | Yes | Yes | Yes | Yes |
find()
není podporována v aplikaci Internet Explorer 11 (nebo starší).
Příklad 2
Najděte hodnotu prvního prvku, který má hodnotu nad konkrétním číslem:
<p><input type="number" id="ageToCheck" value="18"></p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
const ages = [4, 12, 16, 20];
function checkAge(age) {
return age > document.getElementById("ageToCheck").value;
}
function myFunction() {
document.getElementById("demo").innerHTML = ages.find(checkAge);
}
</script>