js字典对象_js实现字典Dictionary类操作
什么是字典?
字典(Dictionary)是一种以 键-值对 形式存储数据的数据结构 ,就如同我们平时查看通讯录一样,要找一个电话,首先先找到该号码的机主名字,名字找到了,紧接着电话号码也就有了。这里的键就是你用来查找的东西,本例中指代的就是名字,值就是查找得到的结果,也就是对应的电话号码。
其实对于javascript来说,字典类(Dictionary)的基础是Array类,js中的Array既是一个数组,同时也是一个字典。
字典的实现
字典(Dictionary)类的基础是 Array 类。同之前的我们所看到的数据结构一样,字典类也应该有添加、删除、清空等操作。代码如下:
/*字典 Dictionary类*/
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 str = "";
for(var key in this.datastore) {
str += key + " -> " + this.datastore[key] + "; "
}
console.log(str);
}
function count() {
/*var ss = Object.keys(this.datastore).length;
console.log("ssss "+ss);
return Object.keys(this.datastore).length;*/
/**/
var n = 0;
for(var key in Object.keys(this.datastore)) {
++n;
}
console.log(n);
return n;
}
function clear() {
for(var key in this.datastore) {
delete this.datastore[key];
}
}
var pbook = new Dictionary();
pbook.add("Mike", "723");
pbook.add("Jennifer", "987");
pbook.add("Jonathan", "666");
pbook.showAll();//Mike -> 723; Jennifer -> 987; Jonathan -> 666;
pbook.count();//3
pbook.remove("Jennifer");
//pbook.clear();
pbook.showAll();//Mike -> 723; Jonathan -> 666;
pbook.count();//2本文内容仅供个人学习/研究/参考使用,不构成任何决策建议或专业指导。分享/转载时请标明原文来源,同时请勿将内容用于商业售卖、虚假宣传等非学习用途哦~感谢您的理解与支持!