javascritp封装的类似java HashMap的类

时间:2021-11-14 13:19:12
function Map(){
this.init();
};
//map的大小
Map.prototype.size = function(){
return this._size;
};
//将数据放入map中
Map.prototype.put = function(key,value){
if(!this.containsKey(key)){
this.array[key] = value;
this._size++;
}
};
//根据key获得map的其中一个value
Map.prototype.get = function(key){
return this.array[key];
};
//map是否为空集合
Map.prototype.isEmpty = function(){
return this._size === 0;
};
//map集合是否包含key
Map.prototype.containsKey = function(key){
return this.array[key]!==undefined?true:false;
};
//移除指定的key
Map.prototype.remove = function(key){
if(this.containsKey(key)){
delete this.array[key];
this._size--;
}
};
//移除所有集合
Map.prototype.clear = function(){
this.init();
};
//map集合转化成Array
Map.prototype.toArray = function(){
return this.array;
};
//初始化map集合
Map.prototype.init = function(){
this.array = new Array();
this._size = 0;
this._keySet = new Array();
};

用法如下:

var map = new Map();
map.put("lynn","25");
map.put("min","24");
map.put("min1",0);
map.remove("min");
var arr = map.toArray();
for(var i in arr){
alert(map.get(i));
}