تعلم Methods و Objects الـ JavaScript الأساسية
تم التحديث: ٢٧ مارس ٢٠٢٦
ملخص
أتقن الأساليب الأساسية لـ JavaScript — عمليات المصفوفات (Array) مثل (map، filter، reduce، groupBy)، ومعالجة النصوص (String)، وأدوات الكائنات (Object)، وهياكل البيانات Map/Set، وأنماط الوعود (Promise) — لكتابة كود فعال وقابل للقراءة في جميع أنواع المشاريع.
تعد المكتبة القياسية لـ JavaScript واسعة النطاق، ومعرفة الأساليب التي يجب استخدامها هي ما يميز المطورين المبتدئين عن المحترفين. ينظم هذا الدليل المرجعي الأساليب الأساسية حسب الفئة مع أمثلة عملية وتوقيعات أنواع TypeScript. سواء كنت تقوم بمعالجة البيانات، أو التلاعب بالنصوص، أو تنظيم العمليات غير المتزامنة، ستصبح هذه الأنماط جزءاً من ذاكرتك العضلية.
أساليب المصفوفات (Array Methods)
التكرار والتحويل
const numbers = [1, 2, 3, 4, 5];
// map: transform each element
const doubled = numbers.map(n => n * 2);
console.log(doubled); // [2, 4, 6, 8, 10]
// filter: keep elements that match a condition
const evens = numbers.filter(n => n % 2 === 0);
console.log(evens); // [2, 4]
// reduce: aggregate to a single value
const sum = numbers.reduce((acc n) => acc + n, 0);
console.log(sum); // 15
// forEach: execute side effects (no return value)
numbers.forEach((n index) => {
console.log(`Index ${index}: ${n}`);
});
توقيعات TypeScript:
// map<U>(callback: (value: T, index: number, array: T[]) => U): U[]
const squared: number[] = numbers.map(n => n * n);
// filter<S extends T>(predicate: (value: T, index: number, array: T[]) => value is S): S[]
const filtered: number[] = numbers.filter(n => n > 2);
// reduce<U>(callback: (prev: U, curr: T, index: number, array: T[]) => U, init: U): U
const total: number = numbers.reduce((sum n) => sum + n 0);
البحث عن العناصر
const users = [
{ id: 1 name: 'Alice' role: 'admin' }
{ id: 2 name: 'Bob' role: 'user' }
{ id: 3 name: 'Charlie' role: 'user' }
];
// find: return first matching element
const admin = users.find(u => u.role === 'admin');
console.log(admin); // { id: 1, name: 'Alice', role: 'admin' }
// findIndex: return index of first match
const idx = users.findIndex(u => u.id === 2);
console.log(idx); // 1
// includes: check if value exists
const hasZero = [1 2 3].includes(0);
console.log(hasZero); // false
// some: test if at least one element matches
const hasAdmin = users.some(u => u.role === 'admin');
console.log(hasAdmin); // true
// every: test if all elements match
const allActive = users.every(u => u.active !== false);
console.log(allActive); // true (if no explicit false values)
التجميع والتلخيص (ES2024)
const transactions = [
{ id: 1 type: 'income' amount: 100 }
{ id: 2 type: 'expense' amount: 50 }
{ id: 3 type: 'income' amount: 200 }
{ id: 4 type: 'expense' amount: 30 }
];
// Object.groupBy: group by key function (ES2024 — note: Array.groupBy was
// withdrawn due to web-compat issues; use the static Object.groupBy instead)
const byType = Object.groupBy(transactions t => t.type);
console.log(byType.income); // [{ id: 1, ... }, { id: 3, ... }]
// Combining groupBy with reduce
const totals = Object.entries(
Object.groupBy(transactions t => t.type)
).reduce((acc [type items]) => {
acc[type] = items.reduce((sum t) => sum + t.amount 0);
return acc;
} {});
console.log(totals); // { income: 300, expense: 80 }
التسطيح والربط
// flat: flatten nested arrays
const nested = [1 [2 3] [4 [5 6]]];
console.log(nested.flat()); // [1, 2, 3, 4, [5, 6]] — flattens one level
console.log(nested.flat(2)); // [1, 2, 3, 4, 5, 6] — flattens two levels
// flatMap: map and flatten in one pass
const sentences = ['Hello world' 'Nice day'];
const words = sentences.flatMap(s => s.split(' '));
console.log(words); // ['Hello', 'world', 'Nice', 'day']
// join: combine array elements into string
const csv = ['Alice' 'Bob' 'Charlie'].join(', ');
console.log(csv); // 'Alice, Bob, Charlie'
أساليب النصوص (String Methods)
البحث والتحقق
const text = 'Hello, JavaScript!';
// includes: check if substring exists
console.log(text.includes('Java')); // true
// startsWith / endsWith: check string boundaries
console.log(text.startsWith('Hello')); // true
console.log(text.endsWith('!')); // true
// indexOf / lastIndexOf: find position
console.log(text.indexOf('o')); // 4
console.log(text.lastIndexOf('o')); // 14
// search: find with regex
console.log(text.search(/script/i)); // 7 — case insensitive
// match: find all matches with regex
const matches = 'abc123def456'.match(/\d+/g);
console.log(matches); // ['123', '456']
التحويل
// toUpperCase / toLowerCase
console.log('hello'.toUpperCase()); // 'HELLO'
console.log('HELLO'.toLowerCase()); // 'hello'
// trim: remove whitespace
console.log(' spaced '.trim()); // 'spaced'
console.log(' spaced '.trimStart()); // 'spaced '
console.log(' spaced '.trimEnd()); // ' spaced'
// replace / replaceAll: substitute strings
console.log('hello world'.replace('world' 'JS')); // 'hello JS'
console.log('hello world world'.replaceAll('world' 'JS')); // 'hello JS JS'
// split: divide string into array
console.log('a,b,c'.split(',')); // ['a', 'b', 'c']
console.log('hello'.split('')); // ['h', 'e', 'l', 'l', 'o']
// slice / substring: extract portions
const str = 'JavaScript';
console.log(str.slice(0 4)); // 'Java'
console.log(str.substring(0 4)); // 'Java'
القوالب والحشو (Padding)
// Template literals (backticks) — not a method, but essential
const name = 'Alice';
const age = 30;
console.log(`${name is ${age years old`); // 'Alice is 30 years old'
// padStart / padEnd: pad strings to length
console.log('5'.padStart(3 '0')); // '005'
console.log('5'.padEnd(3 '0')); // '500'
// repeat: repeat string
console.log('ab'.repeat(3)); // 'ababab'
أساليب الكائنات (Object Methods)
الفحص الذاتي والتكرار
const user = {
id: 1
name: 'Alice'
email: 'alice@example.com'
};
// Object.keys: array of property names
console.log(Object.keys(user)); // ['id', 'name', 'email']
// Object.values: array of property values
console.log(Object.values(user)); // [1, 'Alice', 'alice@example.com']
// Object.entries: array of [key, value] pairs
Object.entries(user).forEach(([key value]) => {
console.log(`${key: ${value`);
});
// Object.hasOwn: check if property exists (modern version of hasOwnProperty)
console.log(Object.hasOwn(user 'name')); // true
console.log(Object.hasOwn(user 'age')); // false
الدمج والتوسيع
const defaults = { timeout: 5000 retries: 3 };
const config = { timeout: 10000 };
// Object.assign: merge objects (mutates first argument)
const merged = Object.assign({} defaults config);
console.log(merged); // { timeout: 10000, retries: 3 }
// Spread operator: cleaner syntax
const merged2 = { ...defaults ...config };
console.log(merged2); // { timeout: 10000, retries: 3 }
// Deep merge (manual recursion required)
function deepMerge(target source) {
Object.entries(source).forEach(([key value]) => {
if (value && typeof value === 'object' && !Array.isArray(value) {
target[key] = target[key] || {};
deepMerge(target[key value);
} else {
target[key] = value;
}
});
return target;
}
التحويل
const users = [
{ id: 1 name: 'Alice' role: 'admin' }
{ id: 2 name: 'Bob' role: 'user' }
{ id: 3 name: 'Charlie' role: 'user' }
];
// Create a lookup map by ID
const byId = Object.fromEntries(
users.map(u => [u.id u])
);
console.log(byId[1]); // { id: 1, name: 'Alice', ... }
// Transform values
const upperNames = Object.fromEntries(
Object.entries({ a: 'alice' b: 'bob' } .map(([k v]) => [k v.toUpperCase(])
);
console.log(upperNames); // { a: 'ALICE', b: 'BOB' }
// Group by property
const byRole = Object.groupBy(users u => u.role);
console.log(byRole.admin; // [{ id: 1, ... }]
Map و Set
Map: تخزين مفتاح-قيمة
// Map preserves key type and insertion order
const map = new Map<string number>(;
// set: add or update entry
map.تابع التعلم
مقالات ذات صلة
ابقَ على مسار النيرد
بريد واحد أسبوعياً — دورات، مقالات معمّقة، أدوات، وتجارب ذكاء اصطناعي.
بدون إزعاج. إلغاء الاشتراك في أي وقت.