This article illustrates the use of array and object to implement a map in JavaScript. Share to everyone for your reference. as follows:
Yesterday, I suddenly saw other people using JavaScript to realize the map is very good, but found that there are some problems, by the way perfect, add remove, indexOf, values, clear and other methods.
/** * @author blune68 * @version 0.1, 07/27/12 * * */function Map () {This.keys = new Array ();
This.data = new Object ();
var toString = Object.prototype.toString;
/** * Current Map Current length */this.size = function () {return this.keys.length; /** * Add Value * @param {object} Key * @param {Object} value */this.put = function (key, value) {if (this.
Data[key] = = null) {This.data[key] = value;
} this.keys.push (key);
/** * Get value * @param {Object} key/this.get = function (key) {return This.data[key] based on current key; /** * removes map corresponding value from current key * @param {Object} key/this.remove = function (key) {var index = this.indexof (ke
y);
if (index!=-1) {This.keys.splice (index, 1);
} This.data[key] = null; /** * Empty Map * * * this.clear = function () {for (var i=0, len = This.size (); i < Len; i++) {var key =
This.keys[i];
This.data[key] = null;
} this.keys.length = 0; }
/** The current key exists * @param {Object} key/This.containskey = function (key) {return this.data[key]!= null;
/** * is null/this.isempty = function () {return this.keys.length = = 0;
}/** * Type java map.entryset/this.entryset = function () {var size = this.size ();
var datas = new Array (size);
for (var i = 0, len = size; i < Len; i++) {var key = This.keys[i];
var value = This.data[key];
Datas[i] = {' key ': Key, ' Value ': Value}} return datas;
/** * Traverse the current map * var map = new map ();
* Map.put (' key ', ' value ');
* Map.each (function (index, key, value) {* Console.log ("index:" + index + "--key:" + key + "--value:" + value) *}) * @param {Object} fn/This.each = function (fn) {if (Tostring.call (fn) = = ' [Object function] ') {for (V Ar i = 0, Len = this.size (); i < Len;
i++) {var key = This.keys[i];
FN (i, key, This.data[key]);} return null;
/** * Gets the current key index value in the map * @param {Object} key/this.indexof = function (key) {var size = this.size ();
if (Size > 0) {for (Var i=0, len=size i < Len; i++) {if (this.keys[i] = = key) return i;
}} return-1;
/** * Override toString */this.tostring = function () {var str = "{";
for (var i = 0, Len = this.size (); i < Len; i++, str+= ",") {var key = This.keys[i];
var value = This.data[key];
STR + + key + "=" + value;
str = str.substring (0, str.length-1);
str + = "}";
return str;
/** * Gets all value values (Array)/this.values = function () {var size = This.size () in the map;
var values = new Array ();
for (var i = 0; i < size; i++) {var key = This.keys[i];
Values.push (This.data[key]);
return values;
}
}
The
wants this article to help you with your JavaScript programming.