字典是一種以 key-value 對形式儲存資料的資料結構,就像身分證上的 ID 與名字一樣,找到 ID 也就確定了名字。JavaScript 的 Object 類就是以字典形式設計的。
Dictionary 類的基礎是 Array 類,而不是 Object 類。
function Dictionary() {
this.datastore = new Array();
}
定義 add() 方法,接受 key 與 value 兩個參數,key 是 value 在字典中的索引:
function add(key, value) {
this.datastore[key] = value;
}
定義 find() 方法,以鍵為參數,回傳與其關聯的值:
function find(key) {
return this.datastore[key];
}
使用內建的 delete 刪除 key-value 對,以此定義 remove() 方法:
function remove(key) {
delete this.datastore[key];
}
再寫一個顯示字典中所有 key-value 對的 showAll() 方法,以及統計元素個數的 count() 方法:
function showAll() {
for (var key in Object.keys(this.datastore)) {
console.log(key + " -> " + this.datastore[key]);
}
}
function count() {
var n = 0;
for (var key in Object.keys(this.datastore)) {
++n;
}
return n;
}
透過這些方法,就能建立、查詢、刪除、統計字典中的資料,還可以定義 clear() 方法一次清空所有內容,是一個實用而直觀的資料結構練習。