字典是一种以键值对形式存储数据的数据结构,这里的键是指用来查找的东西,值是查找得到的结果
代码如下
function Dictionary(){
this.add = add;
this.dataStore = new Array();
this.find = find;
this.remove = remove;
this.showAll = showAll;
this.count = count;
this.clear = clear;
}
function add(key, value){
this.dataStore[key] = value;
}
function find(key){
return this.dataStore[key];
}
function remove(key){
delete this.dataStore[key];
}
function showAll(){
var keys = Object.keys(this.dataStore);
//调用Object类的keys方法可以返回传入参数中存储的所有键
for(var i in keys){
console.log(keys[i] + "->" + this.dataStore[keys[i]]);
}
}
function count(){
var n = 0;
for(var key in Object.keys(this.dataStore)){
++n;
}
return n;
}
function clear(){
var keys = Object.keys(this.dataStore);
for(var i in keys){
delete this.dataStore[keys[i]];
}
}
//测试一下!
var books = new Dictionary();
books.add("math", "12");
books.add("english", "3");
books.add("chinese", "2");
books.add("pe", "12000");
console.log("字典中的元素个数:" + books.count());
console.log("english在字典中对应的值:" + books.find("english"));
books.showAll();
books.remove("chinese");
console.log("执行过删除元素操作后字典中的元素个数:" + books.count());
books.showAll();
books.clear();
console.log("字典中的元素个数:" + books.count());
运行结果