2.工具篇 Dictionary

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_27032631/article/details/87940058

具有key-value的数据存储功能 主要重要与List类型 数据储存

如果有需要可以在此基础 适当扩展

文件名 dictionnary

/**
 * 字典
 */

   //申明一个字典对象
   function dictionary() {
      this.count=0;
        this.keys = new Array();
        this.values = new Array();
    }

   //检查是否存在某个key值
    dictionary.prototype.containKey=function(key){
        var index = this.checkKeyId(key);
        if(index != -1)
        {
            return true;
        }
        return false;
    },

  // 添加key-value数据
    dictionary.prototype.add=function(key,value){
        var index = this.checkKeyId(key);
        if(index != -1)
        {
            //print(key + " is exit");
            //alert(key + " is exit");
            console.log(this);
            console.log(key + " is exit");
            return;
        }       
        this.keys[this.count] = key;
        this.values[this.count] = value;
        ++this.count;
        // console.log(key+":"+value);
    },
   //根据key值移除数据
    dictionary.prototype.remove=function(key){
        var index = this.checkKeyId(key);
        if(-1==index)
        {
            console.log(key+" does not exist");
            return;
        }
        this.keys.splice(index,1);
        this.values.splice(index,1);
        --this.count;
    }
    //根据key值获取数据
    dictionary.prototype.get=function(key){
        var index = this.checkKeyId(key);
        if(-1==index)
        {
            console.log(key+" does not exist:");
            return null;
        }
        return this.values[index];
    }
    //检查是否存在当前key值
    dictionary.prototype.checkKeyId=function(key){
        for(var i=0;i<this.count;i++)
        {
            if(key==this.keys[i])
            {
                return i;
            }
        }
        return -1;
    }
    //根据索引值获得一个value值
    dictionary.prototype.getNameByIndex = function(index)
    {
        return this.keys[index];
    }

module.exports = dictionary;

猜你喜欢

转载自blog.csdn.net/qq_27032631/article/details/87940058