Java 有 Map、List 等現成的集合類別,用起来相當順手;而在 JavaScript 中,我們長久以來只能拿 Array 或 Object 來湊合。以下示範如何自製一個 Map 物件,用字串當鍵、任意型別當值,並提供 put、get、remove 等操作。
/**
* @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;
};
};
var map = new Map();
map.put("a", "a");
alert(map.get("a")); // a
map.put("a", "b"); // 後者覆蓋前者
alert(map.get("a")); // b
其他方法(remove、contains、getCount、clear)可自行試寫驗證。
整個類別的核心是 _getIndex():put、get、remove、contains 全都先靠它線性搜尋找出位置,再決定動作。以底線開頭的命名慣例表示「內部方法,外部不該直接呼叫」。
這個實作有兩個明顯限制值得知道:
查找是 O(n)。每次操作都要逐一比對,資料量大時效能會明顯下降。原生 Object 與 Map 是靠雜湊表實作,查找接近 O(1)。
鍵只能是字串。程式中用 === 嚴格比較,物件型別的鍵會因為參照不同而永遠找不到。
ES6 已經內建了 Map,功能完整、效能優良,不必再自行打造:
var map = new Map();
map.set("a", 1);
map.set("a", 2); // 自動覆寫
console.log(map.get("a")); // 2
console.log(map.has("a")); // true
map.delete("a");
console.log(map.size); // 0
map.clear();
// Map 的鍵可以是任意型別,包含物件
var key = { id: 1 };
map.set(key, "任何值都能當鍵");
console.log(map.get(key));
// 可直接走訪
map.forEach(function (value, key) {
console.log(key, value);
});
for (var entry of map) {
console.log(entry[0], entry[1]);
}
與舊式 Object 相比,原生 Map 的優勢是:鍵不限於字串、能可靠地統計項目數量(size)、維持插入順序、且不會與 Object.prototype 上的既有屬性名稱碰撞。
若你的環境必須支援很舊的瀏覽器而無法使用 Map,上面這份自製實作仍可作參考;但在現代專案中,優先選擇原生 Map 會省去不少維護成本。