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

สร้าง Associative Array ใน JavaScript

Associative Array ใน JS คือ Object ที่ใช้ Key แทน Index ใช้ Array of Objects

ตัวอย่างโค้ด

var customerDetails = [
    { "customerId": "customer-1", "customerName": "David", "customerCountryName": "US" },
    { "customerId": "customer-2", "customerName": "Bob", "customerCountryName": "UK" },
    { "customerId": "customer-3", "customerName": "Carol", "customerCountryName": "AUS" }
];

for (var i = 0; i < customerDetails.length; i++) {
    console.log(customerDetails[i].customerName);
}

วิธีรันโปรแกรม

ใช้คำสั่ง node fileName.js (เช่น node demo115.js)

ผลลัพธ์

David
Bob
Carol