1 <html> 2 <head> 3 <title>Test Map</title> 4 <script type="text/javascript"> 5 <!-- 6 7 /** 8 * Simple Map 9 * 10 * 11 * var m = new Map(); 12 * m.put(‘key‘,‘value‘); 13 * ... 14 * var s = ""; 15 * m.each(function(key,value,index){ 16 * s += index+":"+ key+"="+value+"/n"; 17 * }); 18 * alert(s); 19 * 20 */ 21 function Map() { 22 /** 存放键的数组(遍历用到) */ 23 this.keys = new Array(); 24 /** 存放数据 */ 25 this.data = new Object(); 26 27 /** 28 * 放入一个键值对 29 * @param {String} key 30 * @param {Object} value 31 */ 32 this.put = function(key, value) { 33 if(this.data[key] == null){ 34 this.keys.push(key); 35 } 36 this.data[key] = value; 37 }; 38 39 /** 40 * 获取某键对应的值 41 * @param {String} key 42 * @return {Object} value 43 */ 44 this.get = function(key) { 45 return this.data[key]; 46 }; 47 48 /** 49 * 删除一个键值对 50 * @param {String} key 51 */ 52 this.remove = function(key) { 53 this.keys.remove(key); 54 this.data[key] = null; 55 }; 56 57 /** 58 * 遍历Map,执行处理函数 59 * 60 * @param {Function} 回调函数 function(key,value,index){..} 61 */ 62 this.each = function(fn){ 63 if(typeof fn != ‘function‘){ 64 return; 65 } 66 var len = this.keys.length; 67 for(var i=0;i<len;i++){ 68 var k = this.keys[i]; 69 fn(k,this.data[k],i); 70 } 71 }; 72 73 /** 74 * 获取键值数组(类似Java的entrySet()) 75 * @return 键值对象{key,value}的数组 76 */ 77 this.entrys = function() { 78 var len = this.keys.length; 79 var entrys = new Array(len); 80 for (var i = 0; i < len; i++) { 81 entrys[i] = { 82 key : this.keys[i], 83 value : this.data[i] 84 }; 85 } 86 return entrys; 87 }; 88 89 /** 90 * 判断Map是否为空 91 */ 92 this.isEmpty = function() { 93 return this.keys.length == 0; 94 }; 95 96 /** 97 * 获取键值对数量 98 */ 99 this.size = function(){ 100 return this.keys.length; 101 }; 102 103 /** 104 * 重写toString 105 */ 106 this.toString = function(){ 107 var s = "{"; 108 for(var i=0;i<this.keys.length;i++,s+=‘,‘){ 109 var k = this.keys[i]; 110 s += k+"="+this.data[k]; 111 } 112 s+="}"; 113 return s; 114 }; 115 } 116 117 118 function testMap(){ 119 var m = new Map(); 120 m.put(‘key1‘,‘aaa‘); 121 m.put(‘key2‘,‘bbb‘); 122 m.put(‘key3‘,‘ccc‘); 123 alert("init:"+m); 124 125 m.put(‘key1‘,‘aaaxg‘); 126 alert("set key1:"+m); 127 128 m.remove("key2"); 129 alert("remove key2: "+m); 130 131 var s =""; 132 m.each(function(key,value,index){ 133 s += index+":"+ key+"="+value+"\n"; 134 }); 135 alert(s); 136 } 137 //--> 138 </script> 139 </head> 140 <body> 141 <input type="button" value="test" onclick="testMap()"> 142 </body> 143 </html>
时间: 2024-10-09 02:00:50