直接上代码
function Dictionay() {
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() {
var thisKeysArr = Object.keys(this.datastore).sort();
for (var keyIndex in thisKeysArr) {
var keyName = thisKeysArr[keyIndex];
console.log(keyName, this.datastore[keyName]);
}
}
function clear() {
var thisKeysArr = Object.keys(this.datastore);//得到数字索引数组
for (var keyIndex in thisKeysArr) {
var keyName = thisKeysArr[keyIndex];
delete this.datastore[keyName];
}
}
function count() {
var n = 0;
for (var key in Object.keys(this.datastore)) {
++n;
}
return n;
}
var pbook = new Dictionay();
pbook.add("Raymond","123");
pbook.add('Mike', '123');
pbook.add('David', '345');
pbook.add('Cynthia', '456');
console.log("Number of entries:", pbook.count());
console.log("David's extension:", pbook.find("David"));
pbook.showAll();
pbook.clear();
console.log("Number of entries:", pbook.count());
pbook.remove('ddd');//未报错
运行结果如下:
Number of entries: 4
David's extension: 345
Cynthia 456
David 345
Mike 123
Raymond 123
Number of entries: 0
说明:
showAll()方法中,最终可以得到有序字典。但是,sort()只对数字索引数组有效,对字符串索引的字典无效
。
参考文献
[1] [巴西]Loiane Groner. 学习JavaScript数据结构与算法(第2版)[M]. 人民邮电出版社,2017.