Java 開發者寫 JavaScript 時常有的第一個疑問是:Map 在哪裡?ES6 之前語言本身並沒有 Map,大家只能用 Array 硬湊。既然如此,不如自己封裝一個出來。
這個自訂 Map 內部用一個陣列保存資料,每個元素都是「key + value」的配對物件。key 限定為字串(與 Java 的用法一致),value 則可以是任意型別,並支援 put、get、remove、clear、contains 等基本操作。
/**
* @version 1.0
* 用於實現頁面 Map 對象,Key 只能是 String,對象隨意
*/
var Map = function () {
this._entrys = new Array();
this.put = function (key, value) {
if (key == null || key == undefined) {
return;
}
var index = this._getIndex(key);
if (index == -1) {
var entry = new Object();
entry.key = key;
entry.value = value;
this._entrys[this._entrys.length] = entry;
} else {
this._entrys[index].value = value; // 已存在則覆寫
}
};
this.get = function (key) {
var index = this._getIndex(key);
return (index != -1) ? this._entrys[index].value : null;
};
this.remove = function (key) {
var index = this._getIndex(key);
if (index != -1) {
this._entrys.splice(index, 1);
}
};
this.clear = function () {
this._entrys.length = 0;
};
this.contains = function (key) {
var index = this._getIndex(key);
return (index != -1) ? true : false;
};
this.getCount = function () {
return this._entrys.length;
};
this.getEntrys = function () {
return this._entrys;
};
// 私有方法:找出 key 對應的索引,找不到回傳 -1
this._getIndex = function (key) {
if (key == null || key == undefined) {
return -1;
}
var _length = this._entrys.length;
for (var i = 0; i < _length; i++) {
var entry = this._entrys[i];
if (entry == null || entry == undefined) {
continue;
}
if (entry.key === key) {
return i;
}
}
return -1;
};
}
// 自定義 Map 對象
var map = new Map();
map.put("a", "a");
alert(map.get("a")); // a
map.put("a", "b");
alert(map.get("a")); // b,後者覆蓋前者
關鍵在於 put 會先呼叫 _getIndex 判斷 key 是否已存在:不存在才新增一筆,已存在則直接改寫既有項目的 value。這樣就達成了與 Java Map 一致的「唯一 key」行為。
get 與 put 都是 O(n) 走訪,資料量大時效能會是瓶頸。Map 會更好:查詢為 O(1),且 key 不限於字串,還自帶 forEach、可迭代與 size 屬性。其餘像 getEntrys() 回傳整份配對清單,可以用來做序列化或批次轉換,值得自己動手試寫看看。