一、js对象的基本操作
window.onload=function(){ //创建对象 //var obj = new Object(); var obj={}; //设置属性 obj.name="张安"; obj.age=20; obj["sex"]="男"; obj.say=function(){ alert(this.name); } //访问对象的属性 console.info(obj.name); obj.say(); // delete 删除 对象的属性或方法 delete obj.age; // for in 遍历一个js对象 for(var attribute in obj){ console.info(attribute+"<=======>"+obj[attribute]); } }
使用js模拟java中的map
window.onload=function(){ var map=new Map(); map.put("A","a"); map.put("B","b"); map.put("C","c"); map.put("D",0); var size=map.size();// 4 var value=map.get("D");//d map.eachMap(function(key,value){ alert(key+"______"+value); }); } function Map(){ var obj={}; this.put=function(key,value){ obj[key]=value; }; this.size=function(){ var count=0; for(var attr in obj){ count++; } return count; }; this.get=function(key){ if(obj[key]|| obj[key]===0 ||obj[key]===false){ return obj[key]; }else{ return null; } }; this.remove=function(){ if(obj[key]|| obj[key]===0 ||obj[key]===false){ delete obj[key]; } }; this.eachMap=function(fn){ for(var attr in obj){ fn(attr,obj[attr]); } } }