Menu
Coddy logo textTech
flag Ar iconالعربيةdown icon

دالتا Find و FindIndex

جزء من قسم Logic & Flow في رحلة JavaScript على Coddy — الدرس 58 من 65.

تُرجع الطريقة find() أول عنصر في مصفوفة يحقق دالة اختبار محددة. إذا لم يتم العثور على أي عنصر، فإنها تُرجع undefined.

تُعد طريقة findIndex() مشابهة ولكنها تعيد فهرس أول عنصر مطابق بدلاً من العنصر نفسه. إذا لم يتم العثور على أي عنصر، فإنها تعيد -1.

الصيغة الأساسية:

array.find(callback(element[, index[, array]]))
array.findIndex(callback(element[, index[, array]]))

مثال بسيط مع find():

const numbers = [5, 12, 8, 130, 44];
const found = numbers.find(num => num > 10);
console.log(found);
// 12 (أول رقم أكبر من 10)

نفس المثال مع findIndex():

const numbers = [5, 12, 8, 130, 44];
const foundIndex = numbers.findIndex(num => num > 10);
console.log(foundIndex);
// 1 (فهرس أول رقم أكبر من 10)

البحث عن الكائنات في مصفوفة:

const inventory = [
	{name: 'apples', quantity: 2},
	{name: 'bananas', quantity: 0},
	{name: 'oranges', quantity: 5}
];

// استخدام find
const result = inventory.find(item => item.name === 'bananas');
console.log(result); // {name: 'bananas', quantity: 0}

// استخدام findIndex
const index = inventory.findIndex(item => item.name === 'bananas');
console.log(index); // 1

جرّب بنفسك

لا يتضمّن هذا الدرس تحدّيًا برمجيًا.

quiz iconاختبر نفسك

يتضمن هذا الدرس اختبارًا قصيرًا. ابدأ الدرس للإجابة عليه وتتبّع تقدمك.

جميع دروس Logic & Flow