JavaScript 算法学习第一篇:字典
目录
- what is 字典
- Dictionary类
- 扩展(计数、清楚、排序)
- 使用
what is 字典
字典是一种以键-值对形式存储数据的数据结构。javascript 的 Object类就是以字典形式设计的。
Dictionary类
Dictionary类的基础是 Array 类,而不是 Object 类,因为 js不能对对象的属性进行排序。
// 定义Dictionary类
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];
}
function remove(key) {
delete this.datastore[key];
}
function showAll() {
Object.keys(this.datastore).forEach(key => {
print(key + '->' + this.datastore[key]);
}, this);
}