JavaScript Dizi filtresi()
örnek 1
18 veya daha büyük yaştaki[] tüm değerlerin bir dizisini döndürün:
const ages = [32, 33, 16, 40];
const result = ages.filter(checkAdult);
function checkAdult(age) {
return age >= 18;
}
Tanım ve Kullanım
Yöntem filter()
, bir işlev tarafından sağlanan bir testi geçen öğelerle dolu yeni bir dizi oluşturur.
Yöntem filter()
, boş öğeler için işlevi yürütmez.
Yöntem filter()
, orijinal diziyi değiştirmez.
Sözdizimi
array.filter(function(currentValue, index, arr), thisValue)
parametreler
Parameter | Description |
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. |
Geri dönüş değeri
Tip | Açıklama |
bir dizi |
Testi geçen unsurları içerir. Hiçbir öğe testi geçmezse boş bir dizi döndürür. |
Tarayıcı Desteği
filter()
bir ECMAScript5 (ES5) özelliğidir.
ES5 (JavaScript 2009) tüm tarayıcılarda tam olarak desteklenir:
Chrome | IE | Edge | Firefox | Safari | Opera |
Yes | 9-11 | Yes | Yes | Yes | Yes |
Örnek 2
Belirli bir sayının üzerindeki yaşları[] cinsinden döndürün:
<p><input type="number" id="ageToCheck" value="30"></p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
const ages = [32, 33, 12, 40];
function checkAge(age) {
return age > document.getElementById("ageToCheck").value;
}
function myFunction() {
document.getElementById("demo").innerHTML = ages.filter(checkAge);
}
</script>