字典
字典是一种以键-值对形式存储数据的数据结构。JavaScript的Object类就是以字典的方式设计的,此处将使用Object类本身的特性,实现一个Dictionary类。
1 Dictionary类
Dictionary类的基础是Array类,而不是Object类。
定义:
function Dictionary(){
this.datastore=new Array();
this.add=add;
this.find=find;
this.remove=remove;
this.showAll=showAll;
}
//增加元素 接收两个参数:键和值
function add(key,value){
this.datastore[key]=value;
}
//以键为参数返回和其关联的值
function find(key){
return this.datastore[key];
}
//使用js内置函数delete,该函数是Object类的一部分,使用键的引用作为参数,同时删除键和与其关联的值。
function remove(key){
delete this.datastore[key];
}
//显示字典中所有的键-值对
function showAll() {
for(key in this.datastore){
console.log(key+"->"+this.datastore[key]);
}
//或者
Object.keys(this.datastore).forEach(element=>{
console.log(element+"->"+this.datastore[element]);
});
}
2 Dictionary类的辅助方法
- 返回字典中的元素个数
function count() {
var n = 0;
for(key in this.datastore){
++n;
}
//或者
Object.keys(this.datastore).forEach(element=>{
++n;
});
return n;
}
注意:这里为什么不使用length属性?
- 当键的类型为字符串时,length属性就不管用了。
var nums=new Array();
nums[0]=1;
nums[1]=2;
console.log(nums.length);//2
var pbook=new Array();
pbook["David"]=1;
pbook["Jennifer"]=2;
console.log(pbook.length);//0
- 清空字典中的元素
function clear() {
for(key in this.datastore){
delete this.datastore[key];
}
//或者
Object.keys(this.datastore).forEach(element=>{
delete this.datastore[element];
});
}
3 为Dictionary类添加排序功能
数组本身是可以通过sort()方法排序的,但对于字符串作为键的情况无效。
function showAll(){
Object.keys(this.datastore).sort().forEach(element=>
{
console.log(element+"->"+this.datastore[element]);
});
}