Pole JavaScript findIndex()
Příklad 1
Najděte první prvek s hodnotou vyšší než 18:
const ages = [3, 10, 18, 20];
ages.findIndex(checkAge);
function checkAge(age) {
return age > 18;
}
Definice a použití
Metoda findIndex()
vykonává funkci pro každý prvek pole.
Metoda findIndex()
vrací index (pozici) prvního prvku, který projde testem.
findIndex()
Pokud není nalezena žádná shoda, metoda vrátí -1
.
Metoda findIndex()
neprovádí funkci pro prázdné prvky pole.
Metoda findIndex()
nemění původní pole.
Syntax
array.findIndex(function(currentValue, index, arr), thisValue)
Parametry
Parameter | Description |
function() | Required. A function to be 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 |
Číslo |
Index prvního prvku, který projde testem. Jinak -1. |
Podpora prohlížeče
findIndex()
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 |
findIndex()
není podporována v aplikaci Internet Explorer 11 (nebo starší).
Další příklady
Najděte první prvek s hodnotou nad vstupní hodnotou:
<p><input type="number" id="toCheck" value="18"></p>
<button onclick="myFunction()">Test</button>
<p>Any values above: <span id="demo"></span></p>
<script>
const numbers = [4, 12, 16, 20];
function checkValue(x) {
return x > document.getElementById("toCheck").value;
}
function myFunction() {
document.getElementById("demo").innerHTML = numbers.findIndex(checkValue);
}
</script>