定义
一种以键-值对形式存储数据的数据结构。如:名字-电话号码,通过名字就能找到对应的电话号码,名字就是键(key),电话号就是值(value)。
字典中的键,是值在字典中的索引。
class Dictionary {constructor() {this.items = {};}// 添加一个存储键值对set(key, value) {this.items[key] = value;}// 根据key返回一个itemget(key) {return this.items.hasOwnProperty(key) ? this.items[key] : undefined;}// 删除一个存储键值对remove(key) {if (this.items.hasOwnProperty(key)) {delete this.items[key];}}// 返回字典中 keyget keys() {return Object.keys(this.items);}// 返回字典中 valueget values() {return Object.keys(this.items).reduce((r, c, i) => {r.push(this.items[c]);return r;}, []);}}const dictionary = new Dictionary();dictionary.set("zhangsan", "zhangsan@email.com");dictionary.set("lisi", "lisi@email.com");dictionary.set("zhaowu", "zhaowu@email.com");console.log(dictionary);console.log(dictionary.keys);console.log(dictionary.values);console.log(dictionary.items);console.log("------------------------");dictionary.remove("zhaowu");console.log(dictionary.get("zhaowu"));
