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

Map Object trong JavaScript

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ểmObjectMap
Key typeString/SymbolBất kỳ (object, function, primitive)
Thứ tựKhông đảm bảo (ES2015+ có thứ tự)Insertion order guaranteed
SizeObject.keys(obj).lengthmap.size
Iterationfor...in, Object.keysfor...of, forEach, keys(), values()
Default keysCó prototype keysKhông có key thừa
PerformanceTốt cho staticTốt cho frequent add/delete
JSONJSON.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.