本文共--字 阅读约--分钟 | 浏览: -- Last Updated: 2021-04-27
字典是一种以键-值形式存储数据的数据结构,JavaScript 的 Object 类就是以字典的形式设计的。
下面将实现一个 Dictionary 类,拥有 add 方法,用于添加一个键值对;拥有 find 方法,以键作为参数, 返回对应的值;remove 方法用来删除与给定键关联的键值对;还有一个 showAll 方法用来显示字典中所有的键值对。
function Dictionary() {
this.add = add;
this.dataStore = new Object();
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() {
// 排序输出
Object.keys(this.dataStore).sort().forEach((key) => {
console.log(key + '->' + this.dataStore[key]);
})
}
function count() {
return Object.keys(this.dataStore).length;
}
function clear() {
Object.keys(this.dataStore).forEach((key) => {
delete this.dataStore[key]
})
}
// example
var d = new Dictionary()
d.add('a', 1)
d.add('c', 3)
d.add('e', 5)
d.add('d', 4)
d.add('b', 2)
console.log(d.count()); // 5
d.remove('e')
d.showAll()
// a->1
// b->2
// c->3
// d->4
console.log(d.count()); // 4
d.clear()
console.log(d.count()); // 0