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

เข้าถึง Property ของ JavaScript Object ได้กี่วิธี

เข้าถึง property ของ object ได้ 2 วิธี: Dot notation (.property) และ Bracket notation [property]

รูปแบบที่ 1 - Dot Notation

Object.property;

รูปแบบที่ 2 - Bracket Notation

Object["property"];

ตัวอย่าง: object 'person' เข้าถึง properties ด้วย dot notation

ตัวอย่าง Dot Notation

<html> <body> <script> 
    var person = { 
        firstname: "Ram", 
        lastname: "kumar", 
        age: 50, 
        designation: "content developer" 
    }; 
    document.write(person.firstname + " " + "is in a role of" + " " + person.designation); 
</script> </body> </html>

ผลลัพธ์

Ram is in a role of content developer

ตัวอย่าง: เข้าถึง properties ด้วย bracket notation

ตัวอย่าง Bracket Notation

<html> <body> <script> 
    var person = { 
        firstname: "Ram", 
        lastname: "kumar", 
        age: 50, 
        designation: "content developer" 
    }; 
    document.write(person['firstname'] + " " + "is in a role of" + " " + person['designation']); 
</script> </body> </html>

ผลลัพธ์

Ram is in a role of content developer