JS 原生無 Map (ES6 前),可用對象字面量但鍵只能是字符串。封裝類內部用數組存儲 {key, value} 入口,提供完整 CRUD 接口。
/**
* 簡易 Map 實現,Key 僅限字符串,Value 任意類型
*/
var Map = function(){
this._entrys = []; // 內部存儲數組
// 獲取鍵索引
this._getIndex = function(key){
if(key == null || key === undefined) return -1;
for(var i=0, len=this._entrys.length; i
var map = new Map();
map.put("a", "a");
alert(map.get("a")); // "a"
map.put("a", "b");
alert(map.get("a")); // "b" (覆蓋)
map.put("b", 123);
alert(map.contains("b")); // true
alert(map.getCount()); // 2
map.remove("a");
alert(map.getCount()); // 1
map.clear();
alert(map.getCount()); // 0
const map = new Map();
map.set("a", "a");
map.set("b", {id:1});
console.log(map.get("a")); // "a"
console.log(map.has("b")); // true
console.log(map.size); // 2
map.delete("a");
map.clear();
// 鍵可以是任意類型 (對象、函數、基本類型)
const objKey = {};
map.set(objKey, "object as key");
console.log(map.get(objKey)); // "object as key"
// 遍歷
map.forEach((v,k)=>console.log(k,v));
for(const [k,v] of map) console.log(k,v);
| 特性 | 自定義 Map | ES6 Map |
|---|---|---|
| 鍵類型 | 僅字符串 | 任意類型 |
| 順序保持 | 插入順序 | 插入順序 |
| 性能 | O(n) 查找 | O(1) 平均 |
| 序列化 | 需自定義 | 需手動轉換 |
| 瀏覽器支持 | 所有 | IE11+ / 現代瀏覽器 |