js实现Map结构

	function myMap(){
		var length = 0;
		var obj = new Object();

		/*判断对象中是否包含给定的key*/
		this.containsKey=function(key){
			return (key in obj)
			}

		/*向map中添加数据*/
		this.put = function(key,value){
			if(!this.containsKey(key)){
				length++;
			}
			obj[key] = value;
		}

		/*根据key值获取value*/
		this.get = function(key){
			return this.containsKey(key) ? obj[key] : null;
		}

		/*判断map中是否包含给定的value*/
		this.containsValue = function(value){
			for(var key in obj){
				if(obj[key] == value){
					return true;
				}
			}
			return false;
		}

		/*获取Map中所有key*/
		this.keySet = function(){
			var _keys = new Array();
			for(var key in obj){
				_keys.push(key);
			}
			return _keys;
		}

		/*获取Map的长度*/
		this.size = function(){
			return length;
		}

		/*清空Map*/
		this.clear = function(){
			length = 0;
			obj = new Object();
		}
	}

测试:

	var map = new myMap();
		map.put('name','zhang');
		console.log(map.containsKey('name'));    //true
		console.log(map.get('name'));   //zhang
		console.log(map.keySet());   //["name"]
		console.log(map.size());    //1

猜你喜欢

转载自blog.csdn.net/zhang070514/article/details/83999275
今日推荐