FindIndex () مصفوفة JavaScript
مثال 1
ابحث عن العنصر الأول بقيمة تزيد عن 18:
const ages = [3, 10, 18, 20];
ages.findIndex(checkAge);
function checkAge(age) {
return age > 18;
}
التعريف والاستخدام
الطريقة findIndex()
تنفذ وظيفة لكل عنصر من عناصر المصفوفة.
تُرجع findIndex()
الطريقة فهرس (موضع) العنصر الأول الذي يجتاز اختبارًا.
تقوم findIndex()
الطريقة بإرجاع -1 إذا لم يتم العثور على تطابق.
الطريقة findIndex()
لا تنفذ الوظيفة لعناصر الصفيف الفارغة.
الطريقة findIndex()
لا تغير المصفوفة الأصلية.
بناء الجملة
array.findIndex(function(currentValue, index, arr), thisValue)
المعلمات
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. |
قيمة الإرجاع
نوع | وصف |
رقم |
فهرس العنصر الأول الذي يجتاز الاختبار. خلاف ذلك -1. |
دعم المتصفح
findIndex()
هي إحدى ميزات ECMAScript6 (ES6).
ES6 (JavaScript 2015) مدعوم في جميع المتصفحات الحديثة:
Chrome | Edge | Firefox | Safari | Opera |
Yes | Yes | Yes | Yes | Yes |
findIndex()
غير مدعوم في Internet Explorer 11 (أو أقدم).
مزيد من الأمثلة
ابحث عن العنصر الأول بقيمة أعلى من قيمة الإدخال:
<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>