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

วิธีเข้าถึงค่าออบเจ็กต์ด้วย Variable Key ใน JavaScript

เข้าถึงค่าออบเจ็กต์ได้ 3 วิธี: 1) Dot notation 2) Bracket notation (string key) 3) Variable key (bracket notation ด้วยตัวแปร)

Dot และ Bracket Notation

<html> <body> <script> 
    let me = { name: 'javascript' }; 
    document.write(me.name); 
    document.write("<br>"); 
    document.write(me['name']); 
</script> </body> </html>

ผลลัพธ์

javascript javascript

Variable Key

<html> <body> <script> 
    let me = { name: 'javascript' }; 
    let key = 'name'; 
    document.write(me[key]); 
</script> </body> </html>

ผลลัพธ์

javascript

Variable key เหมาะสำหรับ key ที่決定ได้ตอน runtime