Map Object
Map เก็บ Key-Value Pairs จำลำดับการ Insert ได้ และ Key สามารถเป็น ชนิดข้อมูลใดๆ (Object, Function, Primitive) ได้ ไม่เหมือน Object ธรรมดาที่ Key ต้องเป็น String/Symbol เท่านั้น
ไวยากรณ์
new Map([iterable])
ปัญหาของ Object ธรรมดา (No Map)
<script>
const x = {};
const a = {};
const b = {num: 3};
x[a] = 'a';
x[b] = 'b'; // a และ b ถูก .toString() → '[object Object]' ทั้งคู่!
console.log(JSON.stringify(x)); // {"[object Object]":"b"} - Key a หายไป!
</script>
แก้ด้วย Map
<script>
const a = {};
const b = {num: 3};
const map = new Map();
map.set(a, 'a').set(b, 'b');
for (let [key, value] of map.entries()) {
console.log(key, value); // {} 'a' {num: 3} 'b'
}
console.log(map.size); // 2
console.log(map.has(a)); // true
console.log(map.get(a)); // 'a'
</script>
Map vs Object
| Feature | Map | Object |
|---|---|---|
| Key Types | Any | String/Symbol Only |
| Order | Insertion Order | ไม่รับประกัน (ES2015+ รับประกัน String Key) |
| Size | map.size | Object.keys(obj).length |
| Iteration | for...of ได้เลย | ต้อง Object.keys/entries |
| Default Keys | ไม่มี | Prototype Pollution Risk |
เมื่อไหร่ใช้ Map?
- Key เป็น Object/Function
- ต้องการ Insertion Order
- Add/Delete Key บ่อย (Performance ดีกว่า)
- Key เป็น Unknown/User-generated