Khái niệm
Map (ES2015) là collection key-value pairs, key có thể là bất kỳ kiểu nào (object, function, primitive). Giữ thứ tự insertion, performance tốt hơn Object cho add/delete thường xuyên.
So sánh Map vs Object
| Đặc điểm | Object | Map |
|---|---|---|
| Key type | String/Symbol | Bất kỳ (object, function, primitive) |
| Thứ tự | Không đảm bảo (ES2015+ có thứ tự) | Insertion order guaranteed |
| Size | Object.keys(obj).length | map.size |
| Iteration | for...in, Object.keys | for...of, forEach, keys(), values() |
| Default keys | Có prototype keys | Không có key thừa |
| Performance | Tốt cho static | Tốt cho frequent add/delete |
| JSON | JSON.stringify(obj) | Cần convert: [...map.entries()] |
Ví dụ cơ bản
<!DOCTYPE html>
<html lang="vi">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Map Object</title>
<style>
body { font-family: 'Segoe UI', sans-serif; padding: 20px; }
.result { font-size: 16px; font-weight: 500; color: #6a1b9a; margin: 20px 0; padding: 15px; background: #f3e5f5; border-radius: 4px; white-space: pre-wrap; }
button { padding: 10px 20px; background: #1976d2; color: white; border: none; border-radius: 4px; cursor: pointer; }
</style>
</head>
<body>
<h1>Map Object trong JavaScript</h1>
<div class="result" id="result"></div>
<button id="btn">TẠO & HIỂN THỊ MAP</button>
<h3>Nhấn nút để tạo và hiển thị Map object</h3>
<script>
const resultEle = document.getElementById('result');
const btn = document.getElementById('btn');
// Khởi tạo Map với array của [key, value]
const map1 = new Map([
['name', 'Rohan Sharma'],
['age', 14],
['class', 9]
]);
// Thêm sau
map1.set('city', 'Delhi');
map1.set('hobby', 'Cricket');
btn.addEventListener('click', () => {
resultEle.textContent = '';
for (const [key, value] of map1) {
resultEle.textContent += `${key} = ${value}\n`;
}
resultEle.textContent += `\nSize: ${map1.size}`;
resultEle.textContent += `\nHas 'name': ${map1.has('name')}`;
resultEle.textContent += `\nGet 'age': ${map1.get('age')}`;
});
</script>
</body>
</html>
Kết quả
name = Rohan Sharma age = 14 class = 9 city = Delhi hobby = Cricket Size: 5 Has 'name': true Get 'age': 14
Các Method chính
const map = new Map();
// Thêm/Sửa
map.set('key', 'value');
// Lấy
map.get('key'); // undefined nếu không có
// Kiểm tra
map.has('key'); // boolean
// Xóa
map.delete('key'); // boolean
map.clear(); // xóa tất cả
// Kích thước
map.size; // number
// Iteration
for (const [key, value] of map) { ... }
for (const key of map.keys()) { ... }
for (const value of map.values()) { ... }
map.forEach((value, key, map) => { ... });
// Convert
[...map] // [[key, value], ...]
[...map.keys()] // [key, ...]
[...map.values()] // [value, ...]
Object.fromEntries(map) // {key: value, ...} - ES2019
Key là Object/Function (Đặc biệt của Map)
const objKey = { id: 1 };
const funcKey = () => 'hello';
const map = new Map();
map.set(objKey, 'Object value');
map.set(funcKey, 'Function value');
console.log(map.get(objKey)); // 'Object value'
console.log(map.get(funcKey)); // 'Function value'
// So với Object - key bị toString()
const obj = {};
obj[objKey] = 'value'; // obj['[object Object]'] = 'value'
obj[{id:2}] = 'other'; // GHI ĐÈ! Cùng key '[object Object]'
WeakMap (Đã xem bài trước)
Xem bài WeakMap object in JavaScript để hiểu về weak reference và GC.