经过键值(key-value)对来存储不重复的值的,与集合相比,集合是经过值值(value-value)来存储不重复的值数组
/** - dictionary constructor */ function Dictionary(){ let items = {}; /** * 设置key和对应的值 * @param {*键} key * @param {*值} value */ this.set = function(key, value){ } /** * 删除key对应的value值 * @param {*键} key */ this.remove = function(key){ } /** * 判断是否含有某个键 * @param {*键} key */ this.has = function(key){ } /** * 获取指定键对应的值 * @param {*键} key */ this.get = function(key){ } /** * 清除字典 */ this.clear = function(){ } /** * 获取字典的容量 */ this.size = function(){ } /** * 获取字典中全部的键名,以数组的形式返回 */ this.keys = function(){ } /** * 获取字典中全部的值,以数组的形式返回 */ this.values = function(){ } /** * 获得整个item */ this.getItems = function(){ } }
this.set = function(key, value){ items[key] = value; }
this.has = function(key){ return key in items; }
this.remove = function(key){ if(this.has(key)){ delete items[key]; return true; } return false; }
this.get = function(key){ return this.has(key) ? items[key] : undefined; }
this.clear = function(){ items = {} }
this.keys = function(){ let keys = []; for(key in items){ keys.push(key); } return keys; }
this.size = function(){ return this.keys.length; }
this.values = function(){ const values = []; for(key in items){ values.push(items[keys]); } return values; }
const dic = new Dictionary(); dic.set('name','liumin'); dic.set('age','12'); dic.set('sex','femaile'); console.log(dic.keys()); console.log(dic.values()); console.log(dic.size()); console.log(dic.has('name'));
打印结果:函数