function Dictionary(){
var items = {};
//验证一个key是否是items对象的一个属性
this.has = function(key){
return key in items;
};
//给字典添加一个新的值,或者用来更新一个已有的值
this.set = function(key,value){
items[key] = value;
};
this.remove = function(key){
if(this.has(key)){
delete items[key];
return true;
}
return false;
};
this.get = function(key){
return this.has(key)?items[key]:undefined;
};
this.values = function(){
var values = [];
//遍历items对象的所有属性值
for(var k in items){
//用has函数来验证key确实存在,然后将它的值加入values数组
if(this.has(k)){
values.push(items[k]);
}
}
//返回所有找到的值
return values;
};
//返回items变量的方法
this.getItems = function(){
return items;
};
this.clear = function(){
items = {};
};
this.size = function(){
return Object.keys(items).length;
};
this.keys = function(){
return Object.keys(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'));//返回true
console.log(dictionary.size()); //3
console.log(dictionary.keys());//["Gandalf", "John", "Tyrion"]
console.log(dictionary.values()); //["[email protected]", "[email protected]", "[email protected]"]
console.log(dictionary.get('Tyrion')); //[email protected]
dictionary.remove('John');
console.log(dictionary.keys()); //["Gandalf", "Tyrion"]
console.log(dictionary.values()); // ["[email protected]", "[email protected]"]
console.log(dictionary.getItems()); //{Gandalf: "[email protected]", Tyrion: "[email protected]"}
JavaScript 字典类
猜你喜欢
转载自blog.csdn.net/weixin_37551036/article/details/78929033
今日推荐
周排行