Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> JavaScript

Tạo mảng liên kết (associative array) trong JavaScript

Trong JavaScript, "mảng liên kết" thực chất là **Object** với key do người dùng định nghĩa (thay vì chỉ số số).

Ví dụ: Mảng object làm associative array


var customers = [
    { "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 < customers.length; i++) {
    console.log(customers[i].customerName);
}

Cách chạy

node demo.js

Kết quả


David
Bob
Carol

Cách 2: Object thuần túy (key-value trực tiếp)


var customerMap = {
    "customer-1": { name: "David", country: "US" },
    "customer-2": { name: "Bob", country: "UK" },
    "customer-3": { name: "Carol", country: "AUS" }
};

console.log(customerMap["customer-1"].name); // David

Lưu ý: JS không có associative array thật sự. Dùng Object hoặc Map (key bất kỳ kiểu dữ liệu, giữ thứ tự, size property).