日期:2014-05-16  浏览次数:20311 次

用javaScript做的一个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);
?明天去公司要用这个东西,希望好用啊