代码一:
var map=new map();map.put(a,a);map.put(b,b);map.put(c,c);map.get(a); //返回:amap.entryset() // 返回entity[{key,value},{key,value}]map.containskey('kevin') //返回:false
function map() { this.keys = new array(); this.data = new object(); /** * 放入一个键值对 * @param {string} key * @param {object} value */ this.put = function(key, value) { if(this.data[key] == null){ this.keys.push(key); this.data[key] = value; }else{ this.data[key]=this.data[key]; } return true; }; /** * 获取某键对应的值 * @param {string} key * @return {object} value */ this.get = function(key) { return this.data[key]; }; /** * 删除一个键值对 * @param {string} key */ this.remove = function(key) { for(var i=0;i
array.prototype.remove = function(s) { for (var i = 0; i < this.length; i++) { if (s == this[i]) this.splice(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() { /** 存放键的数组(遍历用到) */ this.keys = new array(); /** 存放数据 */ this.data = new object(); /** * 放入一个键值对 * @param {string} key * @param {object} value */ this.put = function(key, value) { if(this.data[key] == null){ this.keys.push(key); } this.data[key] = value; }; /** * 获取某键对应的值 * @param {string} key * @return {object} value */ this.get = function(key) { return this.data[key]; }; /** * 删除一个键值对 * @param {string} key */ this.remove = function(key) { this.keys.remove(key); this.data[key] = null; }; /** * 遍历map,执行处理函数 * * @param {function} 回调函数 function(key,value,index){..} */ this.each = function(fn){ if(typeof fn != 'function'){ return; } var len = this.keys.length; for(var i=0;i
以上内容通过两段代码给大家分享了javascript中实现map,希望大家喜欢。