JavaScript array trova()
Esempio 1
Trova il valore del primo elemento con un valore maggiore di 18:
const ages = [3, 10, 18, 20];
function checkAge(age) {
return age > 18;
}
function myFunction() {
document.getElementById("demo").innerHTML = ages.find(checkAge);
}
Definizione e utilizzo
Il find()
metodo restituisce il valore del primo elemento che supera un test.
Il find()
metodo esegue una funzione per ogni elemento dell'array.
Il find()
metodo ritorna undefined
se non vengono trovati elementi.
Il find()
metodo non esegue la funzione per gli elementi vuoti.
Il find()
metodo non modifica l'array originale.
Sintassi
array.find(function(currentValue, index, arr),thisValue)
Parametri
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. |
Valore di ritorno
Tipo | Descrizione |
Un valore |
Il valore del primo elemento che supera il test. Altrimenti ritorna undefined . |
Supporto browser
find()
è una funzione ECMAScript6 (ES6).
ES6 (JavaScript 2015) è supportato in tutti i browser moderni:
Chrome | Edge | Firefox | Safari | Opera |
Yes | Yes | Yes | Yes | Yes |
find()
non è supportato in Internet Explorer 11 (o versioni precedenti).
Esempio 2
Trova il valore del primo elemento che con un valore superiore a un numero specifico:
<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>