js辞書の構造を実現します
1593 ワード
//
function Dictionary(){
this.items = {};
//
this.has = function(key){
return this.items.hasOwnProperty(key);
}
//
this.set = function(key,val){
this.items[key] = val;
}
//
this.delete = function(key){
if(this.has(key)){
delete this.items[key];
return true;
}
return false;
}
//
this.get = function(key){
return this.has(key) ? this.items[key] : undefined;
}
//
this.values = function(){
var res = [];
for(var prop in this.items){
if(this.has(prop)){
res.push(this.items[prop]);
}
}
return res;
}
//
this.clear = function(){
this.items = {};
}
//
this.size = function(){
return Object.keys(this.items).length;
}
//
this.keys = function(){
return Object.keys(this.items);
}
//
this.getItems = function(){
return this.items;
}
}
//
var dictionary = new Dictionary();
dictionary.set('Gandalf', '[email protected]');
dictionary.set('John', '[email protected]');
dictionary.set('Tyrion', '[email protected]');
console.log(dictionary.has('Gandalf'));
console.log(dictionary.size());
console.log(dictionary.keys());
console.log(dictionary.values());
console.log(dictionary.getItems());
console.log(dictionary.get('Tyrion'));
dictionary.delete('John');
console.log(dictionary.keys());
console.log(dictionary.values());
console.log(dictionary.getItems());