With JS write a map, with the traversal function, please comment on the next.
Map.js
Array.prototype.remove = function (s) {for (var i = 0; i < this.length; i++) {if (s = = This[i]) this.s
Plice (i, 1);
}/** * Simple map * * * var m = new Map ();
* M.put (' key ', ' value ');
* ... * var s = "";
* M.each (function (key,value,index) {* s + + index+ ":" + key+ "=" +value+ "\ n";
* });
* Alert (s);
* * @author DeWitt * @date 2008-05-24/function Map () {/** The array of keys (traversal used)/This.keys = new Array ();
/** Store Data * * This.data = new Object (); /** * Put a key value pair * @param {String} key * @param {Object} value */this.put = function (key, value) {if (This.data[key] = = null)
{This.keys.push (key);
} This.data[key] = value;
}; /** * Gets the value of a key * @param {String} key * @return {Object} value */this.get = function (key) {return
This.data[key];
}; /** * Delete a key value pair * @param {String} key */this.remove = function (key) {this.keys.remove (key);
This.data[key] = null;
};
/** * Traverse map, perform handler function * @param {function} callback function functions (Key,value,index) {.}
*/This.each = function (fn) {if (typeof fn!= ' function ') {return;
var len = this.keys.length;
for (Var i=0;i<len;i++) {var k = this.keys[i];
FN (k,this.data[k],i);
}
}; /** * Get an array of key values (Java-like EntrySet ()) * @return The array of key-value objects {Key,value}/This.entrys = function () {var len = th
Is.keys.length;
var entrys = new Array (len);
for (var i = 0; i < len; i++) {Entrys[i] = {Key:this.keys[i], value:this.data[i]
};
return entrys;
};
/** * To determine whether the map is empty/this.isempty = function () {return this.keys.length = 0;
};
/** * Gets the key value pair quantity/this.size = function () {return this.keys.length;
};
/** * Rewrite toString */this.tostring = function () {var s = "{"; for (Var i=0;i<this.keys.length;i++,s+= ', ') {var k = this.keys[i];
s + + "=" +this.data[k];
} s+= "}";
return s;
};
function TestMap () {var m = new Map ();
M.put (' Key1 ', ' comtop ');
M.put (' Key2 ', ' Southern Grid ');
M.put (' Key3 ', ' jingxin Garden ');
Alert ("Init:" +m);
M.put (' Key1 ', ' Kang Topu ');
Alert ("Set Key1:" +m);
M.remove ("Key2");
Alert ("Remove Key2:" +m);
var s = "";
M.each (function (key,value,index) {s + = index+ ":" + key+ "=" +value+ "\ n";
});
alert (s);
}//testmap.htm?
The above a simple JavaScript map example (sharing) is a small series to share all the content, hope to give you a reference, but also hope that we support the cloud habitat community.