在字典中,我们使用键值对来存储数据。
字典
字典的定义
Dictionary (map, association list) is a data structure, which is generally an association of unique keys with some values. One may bind a value to a key, delete a key (and naturally an associated value) and lookup for a value by the key.
字典中存储的是[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对象的内部结构
输出的结果如下: