• javaScript实现类似java的Map(没有映射)


    lmap = function() {
    	this.keys = new Array();
    	this.values = new Array();
    };
    
    lmap.prototype = {
    	put : function(key, value) {
    		if (!key)
    			throw 'your key is not valid';
    		for (index in this.values) {
    			if (this.values[index] == null) {
    				this.keys[index] = key;
    				this.values[index] = value;
    				return;
    			}
    		}
    		this.keys[this.keys.length] = key;
    		this.values[this.values.length] = value;
    
    	},
    	getByKey : function(key) {
    		if (!key)
    			throw 'your key is not valid';
    		var index = this.getIndex(key);
    		if (index != -1)
    			return this.values[index];
    		return 'no value for thisKey';
    	},
    	getCount : function() {
    		return this.keys.length;
    	},
    	remove : function(key) {
    		if (!key)
    			throw 'your key is not valid';
    		for (index in this.keys) {
    			if (this.keys[index] == key)
    				this.keys[index] = null;
    			this.values[index] = null;
    		}
    	},
    	contains : function(value) {
    		if (!value)
    			throw 'your value is not valid';
    		for (index in this.values) {
    			if (this.values[index] == value)
    				return true;
    		}
    		return false;
    	},
    	clear : function() {
    		this.keys = new Array();
    		this.values = new Array();
    	},
    	getIndex : function(key) {
    		if (!key)
    			throw 'your key is not valid';
    		for (index in this.keys) {
    			if (this.keys[index] == key)
    				return index;
    		}
    		return -1;
    	}
    };
    
    var theTestMap = new lmap();
    
    theTestMap.put(1, "a");
    theTestMap.put(2, "b");
    theTestMap.put(456, "c");
    theTestMap.put(546, "d");
    theTestMap.put("STRING", "e");
    
    var theMapTestInfo = document.createElement("div");
    theMapTestInfo.innerHTML += 'theTestMap.put(1, "a");<br>'
    		+ 'theTestMap.put(2, "b");<br>' + 'theTestMap.put(456, "c");<br>'
    		+ 'theTestMap.put(546, "d");<br>'
    		+ 'theTestMap.put("STRING", "e");<br>';
    theMapTestInfo.innerHTML += "theTestMap.getByKey(546)===>"
    		+ theTestMap.getByKey(546);
    theMapTestInfo.innerHTML += "<br>theTestMap.contains(\"b\")===>"
    		+ theTestMap.contains("b");
    theMapTestInfo.innerHTML += "<br>theTestMap.getIndex(theKey.sad)===>"
    		+ theTestMap.getIndex("STRING");
    document.body.appendChild(theMapTestInfo);
      
    
     
    

      明天去公司要用,希望不要有问题啊

    天行健君子以自强不息。
  • 相关阅读:
    HDU4289 Control 最大流
    POJ3281 Dining 最大流
    HDU4738 Caocao's Bridges 无向图的桥
    HDU4865 Prince and Princess 强连通分量+二分图判定
    POJ 1904 King's Quest 强连通分量+二分图增广判定
    HDU 4635 Strongly connected 强连通分量
    HDU 4280Island Transport(Dinc非STL 模板)
    POJ 2752Seek the Name, Seek the Fame(next数组妙用 + 既是前缀也是后缀)
    Codeforces Round #346 (Div. 2)E
    POJ2318TOYS(叉积判断点与直线位置)
  • 原文地址:https://www.cnblogs.com/mrye/p/2441482.html
Copyright © 2020-2023  润新知