JavaScript实现的字典
来源:互联网 发布:乐视手机4g网络不稳定 编辑:程序博客网 时间:2024/04/25 08:05
字典中存储的是[key,value],其中键名是用来查询特定的元素的。字典和集合很相似,只是集合以[value,value]的格式来存储数据的。字典也叫作映射。
下面通过一个实际例子来创建并且使用一下字典。
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对象的内部结构
- JavaScript实现的字典
- 数据结构:JavaScript实现字典
- javascript实现字典数据结构
- javascript字典数据结构Dictionary实现
- 数据字典的实现
- 字典树的实现
- 字典树的实现
- redis字典的实现
- redis 字典的实现
- 字典树的实现
- JavaScript字典
- IOS 实现有序的字典
- 字典排序算法的实现
- 字典树的动态实现
- 字典树 Trie 的实现
- 字典树的简单实现
- 字典树的C++实现
- Redis 字典的实现(1)
- Java设计模式--观察者模式
- Inner matrix dimensions must agree 解决方法
- 修改UIAlertAction颜色
- 日期转换JSTL JSP 页面显示日期格式设置
- String,StringBuffer与StringBuilder的区别??
- JavaScript实现的字典
- 深入浅出数据仓库中SQL性能优化之Hive篇
- @Servcie注解出错
- Android自定义View(一)关于super、this和构造方法
- python之从文件读取数据到list
- java运行内存各指标详解
- 指针和结构
- IScroll5实现下拉刷新上拉加载更
- idea mac快捷键