C7 -- 字典
字典是一种以 键-值 对形式存储数据的数据结构。
1.Dictionary类
Dictionary类的基础是Array类,而不是Object类。
我们想对字典中的键进行排序,而JavaScript中是不能对对象的属性进行排序的。键是值在字典中的索引。
JavaScript中的一切皆对象,数组也是对象。
//定义Dictionary类
function Dictionary(){
this.datastore = new Array();
this.add = add;
this.find = find;
this.remove = remove;
this.showAll = showAll;
this.clear = clear;
this.count = count;
}
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(var key in Object.key(this.datastore)){
print(key +'->'+this.datastore[key]);
}
}
//调用Object.keys方法可以返回传入参数存储的所有键。
function count(){
var n = 0;
for(var key in Object.keys(this.datastore)){
++n;
}
return n;
}
当键的类型为字符串时,length属性就不管用了
function clear(){
for each (var key in Object.keys(this.datasore)){
delete this.datastore[key];
}
}
2.为字典类添加排序功能
function showAll(){
for(var key in Object.key(this.datastore).sort()){
print(key +'->'+this.datastore[key]);
}
}