js面向对象开发 (二)js模拟Java中的map

来源:互联网 发布:mac 10.11 替换 matlab 编辑:程序博客网 时间:2024/05/18 07:55
<html>
<head>
<meta http-equiv="Content-Type" content="text/html" charset="utf-8">
<meta name="GENERATOR" content="Microsoft FrontPage 4.0">
<meta name="ProgId" content="FrontPage.Editor.Document">
<title>123</title>
</style>
</head>
<body>
 
</body>
    <script type="text/javascript" charset='utf-8'>
      
//模拟Java中的map对象
function Map(){
var obj = {};//空的对象容器,封装键值对

//map的put方法
this.put = function(key , value){
obj[key] = value;//把键值对绑定到obj对象上
}

//map的获取自身长度大小的方法
this.size = function(){
var count = 0;
for(var attrbite in obj){
count++;
}
return count;
}

//封装map的get方法
this.get = function(key){
if(obj[key] || obj[key] === 0 || obj[key] === false){
return obj[key];
} else {
return null;
}
}

//封装map的remove方法
this.remove = function(key){
if (obj[key] || obj[key] === 0 || obj[key] === false) {
delete obj[key];
}

}

//遍历map的方法   fn为回调函数
this.eachMap = function(fn){
for( var attr in obj){
fn(attr , obj[attr]);
}
}

}

//创建map对象
var map = new Map();
map.put('1' , 'abc');//赋值
map.put('2' , 123);
map.put('3' , false);
map.put('4' , new Date());

alert('use get :'+map.get('3'));
 
//删除map的特定值
map.remove('3');
alert('after delete :'+map.get('3'));

//遍历map参数
map.eachMap(function(key,value){
alert(key+":"+value);//以key:value形式循环输出
});
  
    </script>
</html>
0 0
原创粉丝点击