JavaScript Dizisi findIndex()
örnek 1
18'in üzerinde bir değere sahip ilk öğeyi bulun:
const ages = [3, 10, 18, 20];
ages.findIndex(checkAge);
function checkAge(age) {
return age > 18;
}
Tanım ve Kullanım
Yöntem findIndex()
, her dizi öğesi için bir işlev yürütür.
Yöntem findIndex()
, bir testi geçen ilk öğenin dizinini (konumunu) döndürür.
Eşleşme findIndex()
bulunamazsa yöntem -1 döndürür.
Yöntem findIndex()
, boş dizi öğeleri için işlevi yürütmez.
Yöntem findIndex()
, orijinal diziyi değiştirmez.
Sözdizimi
array.findIndex(function(currentValue, index, arr), thisValue)
parametreler
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. |
Geri dönüş değeri
Tip | Açıklama |
Bir sayı |
Testi geçen ilk öğenin dizini. Aksi takdirde -1. |
Tarayıcı Desteği
findIndex()
bir ECMAScript6 (ES6) özelliğidir.
ES6 (JavaScript 2015) tüm modern tarayıcılarda desteklenir:
Chrome | Edge | Firefox | Safari | Opera |
Yes | Yes | Yes | Yes | Yes |
findIndex()
Internet Explorer 11'de (veya önceki sürümlerde) desteklenmez.
Daha fazla örnek
Giriş değerinin üzerinde bir değere sahip ilk öğeyi bulun:
<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>