經過鍵值(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'));
打印結果:
函數