用js写了一个Map,带遍历功能,请大家点评下啦。
//map.js
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;iTest Map