js中的map
程序员文章站
2024-03-14 16:04:40
...
看到网上很多的js的map实现,也自己实现了一个
// map实现 var map = new Object(); map.put = function (key,value){ var s = "map." + key + ' = "' + value + '";'; eval(s); } map.get = function(key){ var v = eval("map." + key + ";"); return v; } map.keySet = function(){ var keySets = new Array(); for(key in map){ if(!(typeof(map[key])=="function")){ keySets.push(key); } } return keySets; } /* * use example */ /* map.put("a","Tom"); map.put("b","Nick"); var keys = map.keySet(); for(i in keys){ key = keys[i]; alert("key:" + key + " value:" + map.get(key)); } * / /* * end example */
现在,看到了关联数组,可以这用才模拟map
var map = {}; // put var key = "key1"; var value = "value1"; map[key] = value; // get alert(map[key]); if("key1" in map) { //判断是否存在 alert("OK"); } // 删除 delete map["key1"]; // 遍历 for(key in map){ alert(key + map[key]); }
还是这个好用!
原理:
Array本来就是一个 hashmap