Gli ultimi tutorial di sviluppo web
 

JavaScript Filtro Array () Metodo

JavaScript Array di riferimento 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() 9.0 1.5

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:
Argument Description
currentValue Required. The value of the current element
index Optional. The array index of the current element
arr Optional. The array object the current element belongs to
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

Esempi

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 "

JavaScript Array di riferimento JavaScript Array di riferimento