Tablica JavaScript findIndex()
Przykład 1
Znajdź pierwszy element o wartości powyżej 18:
const ages = [3, 10, 18, 20];
ages.findIndex(checkAge);
function checkAge(age) {
return age > 18;
}
Definicja i użycie
Metoda findIndex()
wykonuje funkcję dla każdego elementu tablicy.
Metoda findIndex()
zwraca indeks (pozycję) pierwszego elementu, który przeszedł test.
Metoda findIndex()
zwraca -1, jeśli nie zostanie znalezione żadne dopasowanie.
Metoda findIndex()
nie wykonuje funkcji dla pustych elementów tablicy.
Metoda findIndex()
nie zmienia oryginalnej tablicy.
Składnia
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. |
Wartość zwrotu
Rodzaj | Opis |
Numer |
Indeks pierwszego elementu, który przejdzie test. W przeciwnym razie -1. |
Obsługa przeglądarki
findIndex()
to funkcja ECMAScript6 (ES6).
ES6 (JavaScript 2015) jest obsługiwany we wszystkich nowoczesnych przeglądarkach:
Chrome | Edge | Firefox | Safari | Opera |
Yes | Yes | Yes | Yes | Yes |
findIndex()
nie jest obsługiwany w programie Internet Explorer 11 (lub starszym).
Więcej przykładów
Znajdź pierwszy element z wartością powyżej wartości wejściowej:
<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>