字典是一种以键值对存储数据的一种结构
其实我们可以使用数组和对象去实现字典结构,但是,我们自己定义一个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