ES6 原生提供 Map 對象,但在舊環境或特定需求下,手寫 Map 類有助於理解鍵值存儲原理。本文實現一個功能完整的 Map 類,支援增刪改查、遍歷、序列化等核心操作。
var Map = function() {
this._entries = [];
// 內部查找索引
this._getIndex = function(key) {
if (key == null) return -1;
for (var i = 0, len = this._entries.length; i < len; i++) {
var entry = this._entries[i];
if (entry && entry.key === key) return i;
}
return -1;
};
// 新增/更新
this.put = function(key, value) {
if (key == null) return;
var idx = this._getIndex(key);
if (idx === -1) {
this._entries.push({ key: key, value: value });
} else {
this._entries[idx].value = value;
}
};
// 獲取值
this.get = function(key) {
var idx = this._getIndex(key);
return idx !== -1 ? this._entries[idx].value : null;
};
// 刪除
this.remove = function(key) {
var idx = this._getIndex(key);
if (idx !== -1) this._entries.splice(idx, 1);
};
// 清空
this.clear = function() { this._entries.length = 0; };
// 判斷存在
this.contains = function(key) { return this._getIndex(key) !== -1; };
// 大小
this.size = function() { return this._entries.length; };
// 獲取所有條目
this.entries = function() { return this._entries.slice(); };
// 序列化輸出
this.toString = function() {
return this._entries.map(function(e) {
return e.key + '::' + e.value;
}).join(';');
};
};
var map = new Map();
map.put('name', '張三');
map.put('age', 25);
map.put('city', '北京');
console.log(map.get('name')); // 張三
console.log(map.contains('age')); // true
console.log(map.size()); // 3
console.log(map.toString()); // name::張三;age::25;city::北京
map.remove('age');
console.log(map.size()); // 2
使用數組 _entries 存儲 {key, value} 對象。查找採用線性搜索 O(n),適合中小規模數據。大數據場景建議用對象或 ES6 Map(哈希表 O(1))。
使用 === 比較鍵,區分 1 與 '1',符合 Map 語義。
put 時忽略 null/undefined 鍵;get 未命中返回 null。
// ES6 原生 Map(推薦生產環境)
const map = new Map();
map.set('key', 'value');
map.get('key');
map.has('key');
map.delete('key');
map.size;
map.forEach((v, k) => console.log(k, v));
手寫 Map 類能深入理解鍵值存儲機制。實際項目中優先使用 ES6 Map,它提供更好的性能、鍵類型支援(對象可作鍵)和內置迭代器。本實現適合教學、面試或無法使用 ES6 的舊項目維護。