JS 实现 HashMap

//使用构造器加原型 模式实现一个Map  ,网上有很多实现了,但是都是通过  构造器来实现, 这样每new 一个HashMap ,就会造成 重复函数的创建。造成资源浪费

//var size=0;

var entry=new Object;

function HashMap(){
this.length=0;
};
HashMap.prototype.put=function(key,value){

entry[key]=value;
this.length++;
}
HashMap.prototype.get=function(key){
return this.containsKey(key) ? entry[key] : null;  
}
HashMap.prototype.remove=function(key){
if(this.containsKey(key)&&(delete entry[key])){  
            this.length--;  
        }  
}
HashMap.prototype.containsKey = function ( key )  
    {  
        return (key in entry);  
    } 
HashMap.prototype.size=function(){
return this.length;
}
HashMap.prototype.keySet=function(){  
        var _keys = new Array();  
        for(var key in entry){  
            _keys.push(key);  
        }  
        return _keys;  
    };  
HashMap.prototype.valueSet=function(){  
        var _values = new Array();  
        for(var key in entry){  
            _values.push(entry[key]);  
        }  
        return _values;  
    };  






//  使用HashMap

var map=new HashMap();

map.put("jim",23);
map.put("lily",44);



alert(map.size());


var keys=new Array();
keys=map.keySet();
alert(keys);




var values=new Array();
values=map.valueSet();
alert(values);

猜你喜欢

转载自blog.csdn.net/fei2253/article/details/38734125