非顺序数据结构——字典

做用

经过键值(key-value)对来存储不重复的值的,与集合相比,集合是经过值值(value-value)来存储不重复的值数组

字典所需功能

  • 跟据传入的key-value值向字典中添加元素
  • 经过key移除字典中对应的值
  • 经过某个键来判断是否含有某个值
  • 经过给定的键查找到特定的值并返回
  • 将字典置为空
  • 获取字典的容量
  • 获取字典所包含的全部键,并以数组的形式返回
  • 获取字典所包含的全部值,并以数组的形式返回

代码实现过程

/**
 - 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函数:为字典添加元素
this.set = function(key, value){
         items[key] = value;
    }
  • this.has函数:判断字典是否有某个指定的键
this.has = function(key){
       return key in items;
    }
  • this.remove函数:删除字典中指定的键
this.remove = function(key){
        if(this.has(key)){
           delete items[key];
           return true;
        }
        return false;
    }
  • this.get函数:获取指定键的值
this.get = function(key){
        return this.has(key) ? items[key] : undefined;
    }
  • this.clear函数:清除字典
this.clear = function(){
        items = {}
    }
  • this.key函数:获取字典中全部的键并以数组的形式返回
this.keys = function(){
        let keys = [];
        for(key in items){
            keys.push(key);
        }
        return keys;
    }
  • this.size:获取字典的大小
this.size = function(){
        return this.keys.length;
    }
  • this.values:获取字典中全部的值并以数组的形式返回
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'));

打印结果:
图片描述函数