字典是一種以鍵值對存儲數據的一種結構
其實我們可以使用數組和對象去實現字典結構,但是,我們自己定義一個Dictionary類,讓這種字典類型使用起來更加簡單,使用()來引用鍵更加方便;
定義Dictionary類
function Dictionary(){
this.datastore = new Array();
}
給Dictionary原型添加方法:
Dictionary.prototype = {
//添加方法:
}
一、 添加字典鍵值的方法
add: function(key, value){
this.datastore[key] = value;
}
二、移除某一對鍵值的方法:
remove: function(key){
delete this.datastore[key];
}
三、打印所有鍵值對的方法:
showAll: function(){
console.log(Object.keys(this.datastore));
for (var key in this.datastore){
console.log(key + ':' + this.datastore[key]);
}
}
四、獲取字典中元素的個數
count: function(){
// console.log(this.datastore.length);這個不能用,因爲,當鍵的類型爲字符串時,length不能用
var count = 0;
for (var i in this.datastore){
count ++;
}
return count;
}
五、清空字典的內容
clear: function(){
for (var key in this.datastore){
delete this.datastore[key];
}
六、以鍵值爲一定順序打印
showSortAll: function(){
var keys = Object.keys(this.datastore).sort();
for (var i in keys){
key = keys[i];
console.log(key + ":" + this.datastore[key]);
}
}
實例:
var dic = new Dictionary();
dic.add("c", 3);
dic.add("a", 2);
dic.add("b", 9);
dic.showAll();// c:3 a:2 b:9
dic.remove('a');
dic.showAll();// c:3 b:9
console.log(dic.count());//2
dic.showSortAll(); b:9 c:3
dic.clear();
dic.showAll();// null