字典中存储的是[key,value],其中键名是用来查询特定的元素的。字典和集合很相似,只是集合以[value,value]的格式来存储数据的。字典也叫作映射。
JavaScript实现的字典
下面通过一个实际例子来创建并且使用一下字典。
function Dictionary(){
var 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.has = function(key){
return items.hasOwnProperty(key);
//return value in items;
};
this.get = function(key) {
return this.has(key) ? items[key] : undefined;
};
this.clear = function(){
items = {};
};
this.size = function(){
return Object.keys(items).length;
};
this.keys = function(){
return Object.keys(items);
};
this.values = function(){
var values = [];
for (var k in items) {
if (this.has(k)) {
values.push(items[k]);
}
}
return values;
};
this.each = function(fn) {
for (var k in items) {
if (this.has(k)) {
fn(k, items[k]);
}
}
};
this.getItems = function(){
return items;
}
}
简单地使用字典
var dictionary = new Dictionary();
dictionary.set('Gandalf', 'gandalf@email.com');
dictionary.set('John', 'johnsnow@email.com');
dictionary.set('Tyrion', 'tyrion@email.com');
console.log(dictionary.has('Gandalf'));
console.log(dictionary.size());
console.log(dictionary.keys());
console.log(dictionary.values());
console.log(dictionary.get('Tyrion'));
dictionary.remove('John');
console.log(dictionary.keys());
console.log(dictionary.values());
console.log(dictionary.getItems()); //打印输出items对象的内部结构
来源:oschina
链接:https://my.oschina.net/u/1054538/blog/599229