I have a error about delete this.datastore[key]. I tried to solve the problem. I removed the ‘[key]’ but return wrong value. I want to see Number of entries: 0
at last output. What is the problem ? Thanks for helping comments.
function clear(){
Object.keys(this.datastore).forEach(function(key, index) {
delete this.datastore[key];
});
}
Full Code:
// Updates the complete Dictionary class definition
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 datastore = this.datastore;
Object.keys(this.datastore).forEach( function(key, index) {
console.log(key + " -> " + datastore[key]);
});
}
function count(){
var n = 0;
Object.keys(this.datastore).forEach( function(key, index) {
++n;
});
return n;
}
function clear(){
Object.keys(this.datastore).forEach(function(key, index) {
delete this.datastore[key];
});
}
// Using the count() and clear() functions
var pbook = new Dictionary();
pbook.add("Raymond", "123");
pbook.add("David", "345");
pbook.add("Cynhia", "456");
console.log("Number of entries: " + pbook.count());
console.log("David's extension: " + pbook.find("David") + "\n");
console.log("-------------------------");
pbook.showAll();
pbook.clear();
console.log("Number of entries: " + pbook.count());