字典
字典是一種以鍵 - 值對
形式存儲數據的數據結構,就像電話號碼簿裏的名字和電話號碼一 樣。要找一個電話時,先找名字,名字找到了,緊挨着它的電話號碼也就找到了。
JavaScript 的 Object 類就是以字典的形式設計的。我們嘗試利用obj的特點實現一個帶有字典基本方法的字典類。
一、Dictionary類
爲了方便對字典進行排序,我們要基於數組進行擴展,但要注意數組也是特殊的對昂。
function Dictionary() {
this.datastore = new Array();
}
1.1 定義add()
該方法接受兩個參數:鍵和值。鍵是值在字典中的索引。代碼如下:
function add(key, value) {
this.datastore[key] = value;
}
1.2 定義find()
該方法以鍵作爲參數,返回和其關聯的值。代碼如下所示:
function find(key) {
return this.datastore[key];
}
1.3 定義remove()
以鍵作爲參數,同時刪掉鍵和與其關聯的值
function find(key) {
delete this.datastore[key];
}
1.4 showAll()
顯示所有的鍵-值對
function showAll() {
for(var key in Object.keys(this.datastore)) {
console.log(key + " -> " + this.datastore[key]);
//調用 Object 類的 keys() 方法可以返回傳入參數中存儲的所有鍵。
}
}
二、Dictionary類的輔助方法
2.1 count()——字典中的元素個數
注意,這裏利用Object.key()
而不是.length
,是因爲當key是字符串(arr['nihao']
)時,length屬性不會記錄此數據。
function count() {
var n = 0;
for(var key in Object.keys(this.datastore)) {
++n;
}
return n;
}
2.2 clear()——清空字典
function clear() {
for(var key in Object.keys(this.datastore)) {
delete this.datastore[key]
}
}
三、對Dictionary類進行排序
key-value的形式使得排序並不是必須得,但如果我們希望看到一個有序的字典,怎麼辦?
可以使用 Object.keys() 函數解決這個問題,下面是重新定義的 showAll() 方法:
function showAll() {
for(var key in Object.keys(this.datastore).sort()) {
print(key + " -> " + this.datastore[key]);
}
}
該定義和之前的定義唯一的區別是:從數組 datastore 拿到鍵後,調用 sort() 方法對鍵重 新排了序。
字典類的完整代碼
function Dictionary() {
this.datastore = new Array();
this.add = add;
this.find = find;
this.remove = remove;
this.showAll = showAll;
this.count = count;
this.clear = clear;
}
function add(key, value) {
this.datastore[key] = value;
}
function find(key) {
return this.datastore[key];
}
function remove(key) {
delete this.datastore[key];
}
function showAll() {
for each (var key in Object.keys(this.datastore)) {
print(key + " -> " + this.datastore[key]);
}
}
function count() {
var n = 0;
for each (var key in Object.keys(this.datastore)) {
++n;
}
return n;
}
function clear() {
for each (var key in Object.keys(this.datastore)) {
delete this.datastore[key];
}
}