字典:用【键,值】的形式来存储数据,键名用来查询特定元素。
1.字典所使用的的方法
set(key, value): 向字典中添加元素
remove(key): 移除某个元素
has(key): 检查是否存在某个元素
get(key): 通过键值查询某个元素
clear(): 清除字典中的全部元素
size(): 返回字典中所包含元素的数量
keys(): 将字典中所包含的所有键名以数组返回
values(): 将字典中所包含的所有数值以数组返回
2. 字典的实现
class Dictionary { constructor(){ this.items = {}; } has(key) { return this.items.hasOwnProperty(key); } set(key, value) { this.items[key] = value; } remove(key) { if(this.has(key)){ delete this.items[key]; return true; } return false; } get(key) { return this.has(key)? this.items[key] : undefined; } keys() { return Object.keys(this.items); } values() { return Object.values(this.items); } clear() { this.items = {}; } size() { return Object.keys(this.items).length; } getItems() { return this.items; } } const dictionary = new Dictionary(); dictionary.set(\'lucy\', \'lucy@126.com\'); dictionary.set(\'jack\', \'jack@126.com\'); dictionary.set(\'mike\', \'mike@126.com\'); console.log(dictionary.size()); // 3 console.log(dictionary.has(\'lucy\')); // true console.log(dictionary.get(\'jack\')); // \'jack@126.com\' console.log(dictionary.keys()); // [\'lucy\', \'jack\', \'mike\'] console.log(dictionary.values());// [\'lucy@126.com\', \'jack@126.com\', \'mike@126.com\'] dictionary.remove(\'lucy\'); console.log(dictionary.has(\'lucy\')); // false