Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

การถอดโครงสร้างแบบซ้อน (Nested Destructuring) ใน JavaScript

Destructuring แบบซ้อน (Nested Destructuring) ช่วยให้สามารถแยกค่าจากออบเจ็กต์หรืออาร์เรย์ที่มีโครงสร้างซับซ้อนได้อย่างสะดวก โดยสามารถเข้าถึงค่าลึกภายในได้ในบรรทัดเดียว

ตัวอย่าง: ถอดโครงสร้างออบเจ็กต์และอาร์เรย์แบบซ้อน

<!DOCTYPE html>
<html lang="th">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Nested Destructuring</title>
    <style>
        body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; }
        .sample, .result { font-size: 18px; font-weight: 500; }
        .sample { color: red; }
        .result { color: rebeccapurple; }
        button { padding: 8px 16px; margin: 10px 0; cursor: pointer; }
    </style>
</head>
<body>
    <h1>การถอดโครงสร้างแบบซ้อน (Nested Destructuring)</h1>
    <div class="sample"></div>
    <div class="result"></div>
    <button class="Btn">คลิกเพื่อถอดโครงสร้าง</button>
    <h3>กดปุ่มด้านบนเพื่อถอดโครงสร้างออบเจ็กต์และอาร์เรย์ข้างต้น</h3>

    <script>
        let sampleEle = document.querySelector(".sample");
        let resultEle = document.querySelector(".result");
        
        // ออบเจ็กต์ที่มีโครงสร้างซ้อน
        let obj = {
            Name: {
                firstName: "Rohan",
                lastName: "Sharma"
            },
            age: 22
        };
        
        // อาร์เรย์ที่มีอาร์เรย์ซ้อนภายใน
        let arr = [22, 33, ["a", "b"]];
        
        // แสดงข้อมูลต้นฉบับ
        sampleEle.innerHTML = '{Name:{firstName: "Rohan", lastName: "Sharma"}, age: 22} <br>';
        sampleEle.innerHTML += "[22, 33, ['a', 'b']]";
        
        // Destructuring ออบเจ็กต์แบบซ้อน
        let {
            Name: { firstName, lastName },
            age
        } = obj;
        
        // Destructuring อาร์เรย์แบบซ้อน
        let a, b, c, d;
        [a, b, [c, d]] = arr;
        
        // จัดการเหตุการณ์คลิก
        document.querySelector(".Btn").addEventListener("click", () => {
            resultEle.innerHTML += `firstName=${firstName} lastName=${lastName} age=${age} <br>`;
            resultEle.innerHTML += `a=${a} b=${b} c=${c} d=${d} <br>`;
        });
    </script>
</body>
</html>

ผลลัพธ์

ก่อนกดปุ่ม: แสดงโครงสร้างข้อมูลต้นฉบับ
หลังกดปุ่ม: แสดงค่าที่ถอดโครงสร้างแล้ว เช่น firstName=Rohan lastName=Sharma age=22 และ a=22 b=33 c=a d=b

จุดสำคัญ

  • ใช้วงเล็บปีกกา {} สำหรับออบเจ็กต์ และวงเล็บเหลี่ยม [] สำหรับอาร์เรย์
  • สามารถตั้งชื่อตัวแปรใหม่ได้ด้วยไวยากรณ์ property: newName
  • รองรับการซ้อนหลายระดับได้ไม่จำกัด