JavaScript المتقدم (ES6+)

التفكيك

13 دقيقة الدرس 5 من 40

التفكيك

التفكيك هو إحدى أكثر ميزات ES6 أناقة. يسمح لك باستخراج القيم من المصفوفات والكائنات إلى متغيرات متميزة باستخدام بناء جملة موجز. يغطي هذا الدرس تفكيك المصفوفات، وتفكيك الكائنات، والأنماط المتقدمة التي ستجعل كودك أنظف وأكثر تعبيراً.

أساسيات تفكيك المصفوفات

تفكيك المصفوفات يفك قيم المصفوفة إلى متغيرات منفصلة:

الطريقة القديمة (الوصول بالفهرس): const colors = ["red", "green", "blue"]; const first = colors[0]; const second = colors[1]; const third = colors[2]; الطريقة الجديدة (التفكيك): const colors = ["red", "green", "blue"]; const [first, second, third] = colors; console.log(first); // "red" console.log(second); // "green" console.log(third); // "blue"

يمكنك تخطي العناصر التي لا تحتاجها:

const numbers = [1, 2, 3, 4, 5]; // تخطي العناصر بفتحات فارغة const [first, , third, , fifth] = numbers; console.log(first); // 1 console.log(third); // 3 console.log(fifth); // 5 // احصل فقط على ما تحتاج const [a, b] = numbers; // يأخذ أول عنصرين console.log(a, b); // 1, 2
نصيحة: تفكيك المصفوفات يعمل مع أي قابل للتكرار، بما في ذلك السلاسل والمجموعات والخرائط!

أساسيات تفكيك الكائنات

تفكيك الكائنات يستخرج الخصائص بالاسم:

الطريقة القديمة (تدوين النقطة): const user = { name: "John", age: 25, city: "New York" }; const name = user.name; const age = user.age; const city = user.city; الطريقة الجديدة (التفكيك): const user = { name: "John", age: 25, city: "New York" }; const { name, age, city } = user; console.log(name); // "John" console.log(age); // 25 console.log(city); // "New York"

يجب أن تتطابق أسماء المتغيرات مع أسماء الخصائص (إلا إذا أعدت تسميتها):

const product = { id: 123, title: "Laptop", price: 999 }; // استخراج خصائص محددة const { title, price } = product; console.log(title); // "Laptop" console.log(price); // 999 // إعادة التسمية أثناء التفكيك const { title: productName, price: productPrice } = product; console.log(productName); // "Laptop" console.log(productPrice); // 999
الفرق الرئيسي: تفكيك المصفوفات يستخدم الموضع (الترتيب مهم)، بينما تفكيك الكائنات يستخدم أسماء الخصائص (الترتيب غير مهم).

القيم الافتراضية في التفكيك

قدم قيماً احتياطية للخصائص أو العناصر المفقودة:

مصفوفة مع الافتراضيات: const colors = ["red"]; const [first = "black", second = "white", third = "gray"] = colors; console.log(first); // "red" (من المصفوفة) console.log(second); // "white" (افتراضي) console.log(third); // "gray" (افتراضي)
كائن مع الافتراضيات: const user = { name: "John", age: 25 }; const { name, age, city = "Unknown", country = "USA" } = user; console.log(name); // "John" console.log(age); // 25 console.log(city); // "Unknown" (افتراضي) console.log(country); // "USA" (افتراضي)

الافتراضيات تعمل مع إعادة التسمية:

const settings = { theme: "dark" }; const { theme = "light", fontSize: size = 14, language: lang = "en" } = settings; console.log(theme); // "dark" (من الكائن) console.log(size); // 14 (افتراضي، معاد تسميته من fontSize) console.log(lang); // "en" (افتراضي، معاد تسميته من language)

نمط الباقي في التفكيك

معامل الباقي (...) يجمع العناصر المتبقية:

الباقي في المصفوفات: const numbers = [1, 2, 3, 4, 5]; const [first, second, ...rest] = numbers; console.log(first); // 1 console.log(second); // 2 console.log(rest); // [3, 4, 5]
الباقي في الكائنات: const user = { name: "John", age: 25, city: "New York", country: "USA", email: "john@example.com" }; const { name, age, ...otherInfo } = user; console.log(name); // "John" console.log(age); // 25 console.log(otherInfo); // { city: "New York", country: "USA", email: "john@example.com" }
مهم: يجب أن يكون عنصر الباقي هو العنصر الأخير في التفكيك. const [first, ...rest, last] = arr; غير صالح!

التفكيك المتداخل

فكك الكائنات والمصفوفات المتداخلة:

كائنات متداخلة: const user = { name: "John", age: 25, address: { street: "123 Main St", city: "New York", country: "USA" } }; // فكك العنوان المتداخل const { name, address: { city, country } } = user; console.log(name); // "John" console.log(city); // "New York" console.log(country); // "USA" console.log(address); // ReferenceError: address غير معرف
مصفوفات متداخلة: const data = [1, [2, 3], [4, [5, 6]]]; const [a, [b, c], [d, [e, f]]] = data; console.log(a); // 1 console.log(b); // 2 console.log(c); // 3 console.log(d); // 4 console.log(e); // 5 console.log(f); // 6
تفكيك متداخل مختلط: const response = { status: 200, data: { users: [ { id: 1, name: "John" }, { id: 2, name: "Jane" } ] } }; const { status, data: { users: [firstUser, secondUser] } } = response; console.log(status); // 200 console.log(firstUser); // { id: 1, name: "John" } console.log(secondUser); // { id: 2, name: "Jane" }

التفكيك في معاملات الدالة

واحدة من أقوى استخدامات التفكيك:

معاملات الكائن (معاملات مسماة): // الطريقة القديمة function createUser(name, age, city, country) { // سهل الخلط بين ترتيب المعاملات! console.log(name, age, city, country); } createUser("John", 25, "New York", "USA"); // الطريقة الجديدة مع التفكيك function createUser({ name, age, city, country }) { console.log(name, age, city, country); } // الترتيب غير مهم! createUser({ country: "USA", name: "John", city: "New York", age: 25 });

مع القيم الافتراضية:

function greet({ name = "Guest", greeting = "Hello" } = {}) { console.log(`${greeting}, ${name}!`); } greet({ name: "John" }); // "Hello, John!" greet({ greeting: "Hi" }); // "Hi, Guest!" greet({}); // "Hello, Guest!" greet(); // "Hello, Guest!" (افتراضي كائن فارغ)

تفكيك معامل المصفوفة:

function sumFirstTwo([a, b]) { return a + b; } console.log(sumFirstTwo([5, 3, 10, 20])); // 8 (5 + 3) function processCoordinates([x, y, z = 0]) { console.log(`X: ${x}, Y: ${y}, Z: ${z}`); } processCoordinates([10, 20]); // "X: 10, Y: 20, Z: 0" processCoordinates([10, 20, 30]); // "X: 10, Y: 20, Z: 30"

التطبيقات العملية والأنماط

تبديل المتغيرات: let a = 1; let b = 2; [a, b] = [b, a]; // تبديل بدون متغير مؤقت console.log(a); // 2 console.log(b); // 1
إرجاع قيم متعددة: function getMinMax(numbers) { return { min: Math.min(...numbers), max: Math.max(...numbers) }; } const { min, max } = getMinMax([5, 2, 8, 1, 9]); console.log(min, max); // 1, 9
العمل مع Fetch API: fetch("https://api.example.com/user/123") .then(response => response.json()) .then(({ name, email, avatar }) => { console.log(`Name: ${name}`); console.log(`Email: ${email}`); console.log(`Avatar: ${avatar}`); });
استخراج القيم من المصفوفات: const [year, month, day] = "2024-12-25".split("-"); console.log(year, month, day); // "2024", "12", "25" const url = "https://example.com/products/123"; const [, , , category, id] = url.split("/"); console.log(category, id); // "products", "123"
تفكيك Props في React (نمط شائع): // بدلاً من: function UserCard(props) { return `<h2>${props.name}</h2><p>${props.age}</p>`; } // استخدم التفكيك: function UserCard({ name, age, city = "Unknown" }) { return `<h2>${name}</h2><p>Age: ${age}, City: ${city}</p>`; }
خيارات التكوين: function initializeApp({ theme = "light", language = "en", notifications = true, analytics = false } = {}) { console.log("Theme:", theme); console.log("Language:", language); console.log("Notifications:", notifications); console.log("Analytics:", analytics); } // استخدم مع خيارات جزئية initializeApp({ theme: "dark", analytics: true });

تمرين الممارسة:

أعد كتابة هذا الكود باستخدام التفكيك:

const user = { firstName: "John", lastName: "Doe", age: 25, address: { street: "123 Main St", city: "New York" }, hobbies: ["reading", "coding", "gaming"] }; const firstName = user.firstName; const lastName = user.lastName; const city = user.address.city; const firstHobby = user.hobbies[0]; const secondHobby = user.hobbies[1]; function displayUser(user) { console.log("Name: " + user.firstName + " " + user.lastName); console.log("Age: " + user.age); console.log("City: " + user.address.city); }

الحل:

const user = { firstName: "John", lastName: "Doe", age: 25, address: { street: "123 Main St", city: "New York" }, hobbies: ["reading", "coding", "gaming"] }; // فكك الخصائص على المستوى الأعلى والمتداخلة const { firstName, lastName, address: { city }, hobbies: [firstHobby, secondHobby] } = user; // تفكيك معامل الدالة function displayUser({ firstName, lastName, age, address: { city } }) { console.log(`Name: ${firstName} ${lastName}`); console.log(`Age: ${age}`); console.log(`City: ${city}`); } displayUser(user);

أنماط شائعة في التطبيقات الحقيقية

العمل مع استجابات API: async function fetchUserData(userId) { const response = await fetch(`/api/users/${userId}`); const { data: { user, posts }, status, message } = await response.json(); return { user, posts, status, message }; }
إدارة الحالة (نمط Redux): const state = { user: { name: "John", loggedIn: true }, settings: { theme: "dark", notifications: true }, cart: { items: [], total: 0 } }; const { user: { name, loggedIn }, settings: { theme }, cart: { total } } = state;
التعامل مع قيم الإرجاع المتعددة: function divideWithRemainder(dividend, divisor) { return { quotient: Math.floor(dividend / divisor), remainder: dividend % divisor }; } const { quotient, remainder } = divideWithRemainder(17, 5); console.log(`${quotient} remainder ${remainder}`); // "3 remainder 2"

الملخص

في هذا الدرس، تعلمت:

  • تفكيك المصفوفات يستخرج القيم بالموضع: [a, b, c] = arr
  • تفكيك الكائنات يستخرج القيم بالاسم: { name, age } = obj
  • القيم الافتراضية توفر احتياطيات: { name = "Guest" } = obj
  • معامل الباقي يجمع العناصر المتبقية: { name, ...rest } = obj
  • التفكيك المتداخل يصل إلى الخصائص العميقة
  • تفكيك معامل الدالة ينشئ معاملات مسماة
  • التفكيك يجعل الكود أكثر قابلية للقراءة وتعبيراً
  • أنماط شائعة: تبديل المتغيرات، إرجاعات متعددة، استجابات API
التالي: في الدرس التالي، سنستكشف معاملات النشر والباقي بعمق - أدوات قوية للعمل مع المصفوفات والكائنات!

ES
Edrees Salih
منذ 12 ساعة

We are still cooking the magic in the way!