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

วิธีแก้ไข Property ของ Nested Object ใน JavaScript

แก้ไข property ของ nested object มี 2 วิธี: Dot notation และ Bracket notation ฟังก์ชันเหมือนกัน แตกต่างแค่ notation

Dot Notation

ตัวอย่าง

property country เริ่มเป็น England ใช้ Dot notation เปลี่ยนเป็น India

<html> <body> <script> 
    var person = { 
        "name": "Ram", 
        "age": 27, 
        "address": { 
            "houseno": 123, 
            "streetname": "Baker street", 
            "country": "England" 
        } 
    }; 
    document.write("Before change: " + person.address.country); 
    person.address.country = "India"; 
    document.write("<br>"); 
    document.write("After change: " + person.address.country); 
</script> </body> </html>

ผลลัพธ์

Before change: England After change: India

Bracket Notation

ตัวอย่าง

property country เปลี่ยนจาก England เป็น India ด้วย Bracket notation

<html> <body> <script> 
    var person = { 
        "name": "Ram", 
        "age": 27, 
        "address": { 
            "houseno": 123, 
            "streetname": "Baker street", 
            "country": "England" 
        } 
    }; 
    document.write("Before change: " + person.address["country"]); 
    person.address.country = "India"; 
    document.write("<br>"); 
    document.write("After change: " + person.address["country"]); 
</script> </body> </html>

ผลลัพธ์

Before change: England After change: India