JavaScript 中的 Map

很多编程语言中都有类似Map这种 键-值对 的数据结构。

可惜,JavaScript没有。

幸运的是,可以自己构建一个Map对象。

对象的定义

 1 <script type="text/javascript">
 2 
 3     /** 定义***/
 4     function JSMap() {
 5         var map_ = new Object();
 6         
 7         /*** put **/
 8         map_.put = function(key, value) {
 9             map_[key+'_'] = value;
10         };
11         
12         /*** get **/
13         map_.get = function(key) {
14             return map_[key+'_'];
15         };
16         
17         /*** keyset **/
18         map_.keyset = function() {
19             var ret = "";
20             
21             for(var p in map_) {
22                 if (typeof p == 'string' && p.substring(p.length - 1) == "_") {
23                     ret += ",";
24                     ret += p.substring(0, p.length - 1);
25                 }
26             }
27             
28             if ("" == ret) {
29                 return ret.split(",");
30             } else {
31                 return ret.substring(1).split(",");
32             }
33         }
34         
35         return map_;
36     }
37 </script>

对象的使用

 1 <script type="text/javascript">
 2         /** 应用 **/
 3         var map = new JSMap();
 4         
 5         map.put(1, '一');
 6         map.put("Mon", '星期一');
 7         
 8         /*
 9         alert(map.get(1));
10         alert(map.get("Mon"));
11         alert(map.get("mon"));
12         
13         alert(map.keyset());
14         */
15         
16         /*
17          * 遍历Map
18          */
19         for (var x in map.keyset()) {
20             var key = map.keyset()[x];
21             
22             alert(map.get(key));
23         }
24     </script>

详细代码可参考:https://github.com/YoungZHU/CommonJavaScript/blob/master/aboutMap.html

 


原文地址:https://www.cnblogs.com/memory4young/p/javascript-map.html