zoukankan      html  css  js  c++  java
  • 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);
      
    
     
    

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

    天行健君子以自强不息。
  • 相关阅读:
    Python操作Redis的实例(七)
    Python操作Redis(六)
    Redis的数据类型之set集合,zset有序集合类型操作 (五)
    Redis的数据类型之list列表类型操作 (四)
    Redis的数据类型之hash哈希类型操作 (三)
    Redis的数据类型之String字符串类型操作(二)
    Redis基础介绍以及编译安装过程(一)
    python操作IP---IPy模块
    安装cnpm报错
    vue-cli · Failed to download repo vuejs-templates/webpack: connect ECONNREF
  • 原文地址:https://www.cnblogs.com/mrye/p/2441482.html
Copyright © 2011-2022 走看看