JavaScript ไม่มี Associative Array จริงๆ Array ใน JS ใช้ Numeric Index (0, 1, 2...) เท่านั้น สำหรับ Key-Value ให้ใช้ Object หรือ Map แทน
ตัวอย่างจากบทความ (Array แบบปกติ)
<!DOCTYPE html>
<html>
<body>
<p id="test"></p>
<script>
var dept = [];
dept[0] = "Amit";
dept[1] = "Technical";
dept[2] = 045;
document.getElementById("test").innerHTML = dept[1] + " " + dept.length;
</script>
</body>
</html>
ทำไม Array ไม่ควรใช้เป็น Associative Array
var arr = [];
arr['name'] = 'John';
arr['age'] = 30;
console.log(arr.length); // 0 ❌ (ไม่ใช่ 2!)
console.log(Object.keys(arr)); // ['name', 'age']
console.log(arr[0]); // undefined
// for...in จะวน key string ได้แต่ length = 0
for (let key in arr) {
console.log(key); // 'name', 'age'
}
ทางเลือกที่ถูกต้อง
1. Object (Traditional)
// Object literal
const user = {
name: 'John',
age: 30,
'email-address': 'john@example.com' // key ที่มี special char
};
// Property access
user.name; // 'John' (dot notation)
user['age']; // 30 (bracket notation)
user['email-address']; // ต้องใช้ bracket
// Dynamic keys
const key = 'name';
user[key]; // 'John'
// Methods
Object.keys(user); // ['name', 'age', 'email-address']
Object.values(user); // ['John', 30, 'john@example.com']
Object.entries(user); // [['name', 'John'], ...]
2. Map (ES6 - แนะนำสำหรับ Key-Value)
const map = new Map();
// Set values
map.set('name', 'John');
map.set(123, 'number key'); // Key สามารถเป็น type ใดก็ได้
map.set({id: 1}, 'object key');
// Get values
map.get('name'); // 'John'
map.get(123); // 'number key'
// Properties
map.size; // 3
map.has('name'); // true
map.delete('name'); // true
map.clear(); // ลบทั้งหมด
// Iteration
for (const [key, value] of map) {
console.log(key, value);
}
map.forEach((value, key) => console.log(key, value));
3. Object vs Map - เมื่อไหร่ใช้ไหน
| สถานการณ์ | แนะนำ |
|---|---|
| Fixed schema, known keys | Object |
| Dynamic keys, frequent add/delete | Map |
| Key ไม่ใช่ string (object, function, etc.) | Map |
| ต้องการ size property | Map (มี .size) |
| Iteration order สำคัญ | Map (guaranteed insertion order) |
| JSON Serialization | Object (JSON.stringify) |
| Performance (read-heavy) | Object (เร็วกว่าเล็กน้อย) |
WeakMap / WeakSet (Advanced)
// WeakMap - key ต้องเป็น object, ไม่ป้องกัน garbage collection
const weakMap = new WeakMap();
const obj = {};
weakMap.set(obj, 'metadata');
// เมื่อ obj ไม่มี reference อื่น -> GC สามารถเก็บได้
// ใช้สำหรับ: Private data, Caching, Metadata
สรุป
อย่าใช้ Array เป็น Associative Array
ใช้ Object สำหรับ key-value ทั่วไป (string key)
ใช้ Map สำหรับ dynamic keys, non-string keys, frequent updates