Matrice JavaScript findIndex()
Esempio 1
Trova il primo elemento con un valore superiore a 18:
const ages = [3, 10, 18, 20];
ages.findIndex(checkAge);
function checkAge(age) {
return age > 18;
}
Definizione e utilizzo
Il findIndex()
metodo esegue una funzione per ogni elemento dell'array.
Il findIndex()
metodo restituisce l'indice (posizione) del primo elemento che supera un test.
Il findIndex()
metodo restituisce -1 se non viene trovata alcuna corrispondenza.
Il findIndex()
metodo non esegue la funzione per gli elementi dell'array vuoti.
Il findIndex()
metodo non modifica l'array originale.
Sintassi
array.findIndex(function(currentValue, index, arr), thisValue)
Parametri
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. |
Valore di ritorno
Tipo | Descrizione |
Un numero |
L'indice del primo elemento che supera il test. Altrimenti -1. |
Supporto browser
findIndex()
è una funzione ECMAScript6 (ES6).
ES6 (JavaScript 2015) è supportato in tutti i browser moderni:
Chrome | Edge | Firefox | Safari | Opera |
Yes | Yes | Yes | Yes | Yes |
findIndex()
non è supportato in Internet Explorer 11 (o versioni precedenti).
Altri esempi
Trova il primo elemento con un valore sopra un valore di input:
<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>