- /**
- * 自定义Map对象
- */
- function Map() {
- var mapObj = {};
- this.put = function (key, value) {
- mapObj[key] = value;
- };
- this.remove = function (key) {
- if (mapObj.hasOwnProperty(key)) {
- delete mapObj[key];
- }
- };
- this.get = function (key) {
- if (mapObj.hasOwnProperty(key)) {
- return mapObj[key];
- }
- return null;
- };
- this.getKeys = function () {
- var keys = [];
- for(var k in mapObj){
- keys.push(k);
- }
- return keys;
- };
- // 遍历map
- this.each = function(fn){
- for(var key in mapObj){
- fn(key, mapObj[key]);
- }
- };
- this.toString = function () {
- var str = "{";
- for(var k in mapObj){
- str += "\\""+ k+"\\" : \\""+mapObj[k]+"\\",";
- }
- str = str.substring(0,str.length - 1) ;
- str += "}";
- return str;
- }
- }
- var myMap = new Map();
- myMap.put("a","aaa");
- myMap.put("b",123);
- myMap.put("c",false);
- myMap.put("d",new Date());
- myMap.put("d","dddd");
- myMap.put("e","test");
- myMap.remove("e");
- document.write("myMap.get(\\"a\\") "+myMap.get("a"));
- document.write("<br/>");
- document.write("myMap.get(\\"b\\") "+myMap.get("b"));
- document.write("<br/>");
- document.write("myMap.get(\\"c\\") "+myMap.get("c"));
- document.write("<br/>");
- document.write("myMap.get(\\"d\\") "+myMap.get("d"));
- document.write("<br/>");
- document.write("myMap.toString() "+myMap.toString());
- document.write("<br/>");
- document.write("myMap.getKeys() "+myMap.getKeys());
- document.write("<br/>");
- myMap.each(function (key, value) {
- document.write("each "+key+" = "+value);
- document.write("<br/>");
- });
- //该片段来自于http://www.codesnippet.cn/detail/2601201511638.html
来源: http://www.codesnippet.cn/detail/2601201511638.html