字典是一種以“鍵–值”對形式存儲資料的資料結構。就像電話薄裡的名字和号碼一樣。JavaScript的Object類就是以字典的形式設計的。
一、字典類
字典類(Dictionary)基于Object。在《資料結構與算法JavaScript描述》書中“字典”采用了數組存儲資料,不僅讓閱讀者很難了解,而且也沒有實作便捷性,反而其中的代碼邏輯是錯誤的,不能按照設計的方式正确輸出結果!!!
/**
* 構造函數
* 基于對象存儲資料
* @constructor
*/
function Dictionary(){
this.datastore = new Object();
}
Dictionary.prototype = {
/* 修正constructor */
constructor: Dictionary,
/* 統計個數 */
size: function(){
return Object.keys(this.datastore).length;
},
/* 添加元素,給數組添加屬性 */
add: function(key, value){
this.datastore[key] = value;
},
/* 查找指定key的元素 */
find: function(key){
return this.datastore[key];
},
/* 移除指定key的元素 */
remove: function(key){
delete this.datastore[key];
},
/* 顯示所有的鍵值對 */
showAll: function(){
for(var key in this.datastore){
console.log(key + ": " + this.find(key));
}
}
};
複制
測試:
var dic = new Dictionary();
dic.add("name", "ligang");
dic.add("age", 26);
dic.find("name"); // "ligang"
dic.size(); // 2
dic.showAll(); // "name: ligang" "age: 26"
dic.remove("age");
dic.size(); // 1
dic.showAll(); // "name: ligang"
複制
補充:
Object.keys(obj)
傳回一個數組,包含所有(自身)可枚舉屬性。請檢視-JavaScript對象、函數(你不知道的JavaScript)
二、為字典類添加排序功能
為字典排序,可以轉化為某個對象屬性排序。是以我們可以借助
Object.keys()
/* 排序 */
Dictionary.prototype.sort = function(){
// 借助數組的預設排序
var keys = Object.keys(this.datastore).sort();
// 新定義字典類
var tempDic = new Dictionary();
for(var i = 0, len = keys.length; i < len; i++){
var key = keys[i];
tempDic.add(key, this.find(key));
}
return tempDic;
};
複制
測試:
var dictionary = new Dictionary();
dictionary.add("b", 2);
dictionary.add("a", 1);
dictionary.add("c", 3);
dictionary.showAll(); // "b: 2" "a: 1" "c: 3"
dictionary.sort().showAll(); // "a: 2" "b: 1" "c: 3"
複制
總結:上述字典類不允許出現重複的key。對于相同的key,後面的會覆寫前面的。當然,可以通過修改代碼實作其他方式。