JavaScript模擬的HashMap,請大家多多提意見!

/**
 * V1.0
 * HashMap javascript版
 * 2013-09-04
 
 * 		var map = new $.HashMap();
    		map.put("age","20");
    		map.put("name","yk1");
    		alert(map.get("age"));
    		alert(map.toString());
    		
    		map = new $.HashMap({"username":"ycyk_168","password":"123456"});
    		map.put("age","20");
    		map.put("name","yk1");
    		alert(map.get("username"));
    		alert(map.get("password"));
    		alert(map.get("age"));
    		alert(map.get("name"));
    		alert(map.toString());
 *
 */
jQuery.HashMap = function(param) {
	var _map = typeof(param)=="undefined" ? [{}] : [param];
	/**
	 * 向HashMap中添加數據
	 */
	_map.put =  function(key,value){
		this[0][key] = value;
	};
	
	/**
	 * 從HashMap中獲取指定的Key的值
	 */
	_map.get = function(key){
		return this[0][key];
	};
	
	/**
	 * HashMap中是否包含指定的Key
	 */
	_map.containsKey = function(key){
		return this.get(key) == null ? false : true;
	};
	
	/**
	 * 從HshMap中刪除Key
	 */
	_map.remove = function(key){
		delete this[0][key];
	};
	
	/**
	 * 獲取HashMap的大小
	 */
	_map.size = function(){
		var count = 0;
		for(var item in this[0]){
			count ++;
		}
		return count;
	};
	
	/**
	 * 將HashMap轉換爲string的數據
	 */
	_map.toString = function(){
		var str = "{";
		for(var item in this[0]){
			str += ""+ item +":"+ this[0][item] +",";
		}
		str = $.util.removeEnd(str,",") + "}";
		return str;
	};
	
	/**
	 * 將HashMap轉換爲JSON格式的數據
	 */
	_map.toJson = function(){
		return this[0];
	};
	return _map;
};

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章