js 定义hash类

// JavaScript Document
function HashTable(){
    this._hash={};
    this._count=0;
    
    
    /**
    *添加或者更新key
    */
    this.put=function(key,value){
        if(this._hash.hasOwnProperty(key)){
            this._hash[key]=value;
            return true;
        }else{
                this._hash[key]=value;
                this._count++;
                return true;
            }
    }
    
    
    /**
    *获取key指定的值
    */
    this.get=function(key){
        if(this.containsKey(key))
            return this._hash[key];
    }    
    
    
    /**
    *获取元素个数
    */    
    this.size=function(){
        return this._count;
    }
    
    
    /**
    *检查是否为空
    */
    this.isEmpty=function(){
        if(this._count<=0)
            return true;
        else return false;
    }
    
    
    /**
    *检查是否包含指定的key
    */
    this.containsKey=function(){
            return this._hash.hasOwnPropetry(key);
    }
    
    
    /**
    *检查是否包含指定的value
    */
    this.containsValue=function(){
        for(var strKey in this._hash)
            if(this._hash[strKey]==value)
                return true;                
        return false;
    }
    
    
    /**
    *删除一个key
    */
    this.remove=function(key){
            delete this._hash[key];
            this._count--;
    }
    
    
    /**
    *删除所有的key
    */
    this.clear=function(){
        this._hash={};
        this._count=0;
    }
    
    
    /**
    *从HashTable中获取Key的集合,以数组的形式返回
    */
    this.keySet=function(){
        var arrKeySet= new Array();
        var index=0;
        for(var strKey in this._hash){
            arrKeySet[index++]=strKey;
        }
        return (arrKeySet.length==0)?null:arrKeySet;
    }
    
    
    /**
    *从HashTable中获取Key的集合,以数组的形式返回
    */
    this.values=function(){
        var arrValues= new Array();
        var index=0;
        for(var strKey in this._hash){
            arrValues[index++]=this._hash[strKey];
        }
        return (arrValues.length==0)?null:arrValues;
    }
}

原文地址:https://www.cnblogs.com/hqu-ye/p/3322155.html