您的位置:首页 > 理论基础 > 数据结构算法

数据结构——字典(JavaScript)

2017-07-24 18:51 260 查看

创建字典

function Dictionary(){//首先申明一个类
var items = {};
this.set = function(Key,value){//向字典中添加新元素
items[Key] = value;
}
this.remove = function(Key){//通过使用键值对来从字典中移除键值对应的数据值
if(Key in items){
delete items[Key];
return true;
}else{
return false;
}
}
this.has = function(Key){//如果某个键值存在于这个字典中,就返回true,否则返回false
return Key in items;
}
this.get = function(Key){//通过键值查找指定的数值并返回
return this.has(Key) ? items[Key] : undefined;
}
this.clear = function(){//删除字典中所有的元素
items = {};
return true;
}
this.size = function(){//返回字典所包含元素的数量
return this.Keys().length;
}
this.Keys = function(){
var keys = [];
for(var k in items){
if(this.has(k)){
keys.push(k);
}
}
return keys;
}
this.values = function(){//将字典所包含的所有数值以数组形式返回
var values = [];
for(var k in items){
if(this.has(k)){
values.push(items[k]);
}
}
return values;
}
this.getItems = function(){
return items;
}
}


使用Dictionary类

var dictionary = new Dictionary();
dictionary.set('Tom','123@qq.com');
dictionary.set('Bob','456@163.com');
dictionary.set('John','789@126.com');
console.log(dictionary.has('Tom'));
console.log(dictionary.size());
console.log(dictionary.Keys());
console.log(dictionary.values());
console.log(dictionary.get('Bob'));
console.log(dictionary.remove('John'));
console.log(dictionary.size());
console.log(dictionary.Keys());
console.log(dictionary.values());
console.log(dictionary.getItems());


控制台输出

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  数据结构 javascript