JavaScript Array di riferimento
Esempio
Restituisce un array di tutti i valori nella matrice età che sono 18 anni:
var ages = [32, 33, 16, 40];
function checkAdult(age) {
return age >= 18;
}
function myFunction() {
document.getElementById("demo").innerHTML = ages.filter(checkAdult);
}
Il risultato sarà:
32,33,40
Prova tu stesso " Più "Provate voi stessi" esempi di seguito.
Definizione e utilizzo
Il filter() metodo crea una matrice riempita con tutti gli elementi di matrice che superano una prova (fornito come funzione).
Nota: filtrare () non eseguire la funzione di elementi di un array senza valori.
Nota: filtrare () non cambia la matrice originale.
Supporto per il browser
I numeri nella tabella indicano la prima versione del browser che supporta pienamente il metodo.
metodo | |||||
---|---|---|---|---|---|
filter() | sì | 9.0 | 1.5 | sì | sì |
Sintassi
array.filter( function(currentValue,index,arr), thisValue )
valori dei parametri
Parameter | Description | ||||||||
---|---|---|---|---|---|---|---|---|---|
function(currentValue, index,arr) | Required. A function to be run for each element in the array. Function arguments:
|
||||||||
thisValue | Optional. A value to be passed to the function to be used as
its "this" value. If this parameter is empty, the value "undefined" will be passed as its "this" value |
Dettagli tecnici
Valore di ritorno: | Un array che contiene tutti gli elementi dell'array che superano il test. Se nessun elemento superano il test restituisce un array vuoto. |
---|---|
Versione JavaScript: | 1.6 |

Altri esempi
Esempio
Restituisce un array di tutti i valori nella matrice età che sono un numero specifico o sopra:
<p>Minimum age: <input type="number" id="ageToCheck" value="18"></p>
<button onclick="myFunction()">Try it</button>
<p>All ages above
minimum: <span id="demo"></span></p>
<script>
var ages = [32, 33,
12, 40];
function checkAdult(age) {
return age
>= document.getElementById("ageToCheck").value;
}
function
myFunction() {
document.getElementById("demo").innerHTML = ages.filter(checkAdult);
}
</script>
Prova tu stesso " 