//使用js模拟java中的Map
function Map(){
var obj = {};
this.put = function(key, value){
if(key){
obj[key] = value;
}
};
this.get = function(key){
if(key || obj[key] === 0 || obj[key] === false){
return obj[key];
}
return null;
};
this.size = function(){
var count = 0;
for(var attr in obj){
count++;
}
return count;
};
this.remove = function(key){
//注意此处的判断条件
if(key || obj[key] === 0 || obj[key] === false){
delete obj[key];
}
};
this.each = function(fn){
for(var attr in obj){
fn(attr, obj[attr]);
}
};
this.keys = function(){
var keys = [];
for(var attr in obj){
keys.push(attr);
}
return keys;
};
}
var m = new Map();
m.put("01", "abc");
m.put("02", false);
m.put("03", true);
m.put("04", new Date());
console.info(m.size());
console.info(m.get("02"));
m.remove("03");
console.info(m.get("03"));
m.each(function(key, value){
console.info(key + " --> " + value);
});
转载于:https://my.oschina.net/u/2317126/blog/381268