javascript模拟java中的Map

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.updata = function(key,value){
			obj[key] = value;
		}
		
		// 删除指定属性值
		this.remove = function(key){
			if(obj[key] || obj[key] ===0 || obj[key] ===false)
			delete obj[key]; 
		}
		
		// 根据key值获取value
		this.get = function(key){
			if(obj[key] || obj[key] ===0 || obj[key] ===false){
				return obj[key];
			}else{
				return null;
			}
		}
		
		// 遍历Map
		this.eachMap = function(fn){
			for(var attr in obj){
				fn(attr,obj[attr]);
			}
		}
	}
	
	var map = new Map();
	
	// 添加数据
	map.put("name","wh");
	map.put("age",22);
	alert("添加完map的长度:"+map.size()); // 获取对象长度
	alert("获取name的值:"+map.get("name")); // 根据Key获取Value
	
	// 更新内容
	map.updata("name","whhhhhhhhh");
	alert("修改后name:"+map.get("name"));
	
	// 删除属性
	map.remove("age");
	alert("删除后map长度"+map.size());
	
	// 遍历对象
	map.eachMap(function(key,value){
		alert("遍历获取键值对---"+key+" : "+value);
	});

猜你喜欢

转载自blog.csdn.net/u014505277/article/details/52610261