写自己的js的Map类
众所周之,js是没有Map类的,要想用还得自己封装一个。
(function(win) { var Map = function() { this.count = 0; this.entrySet = {}; }; var proto = Map.prototype; proto.size = function() { return this.count; }; proto.isEmpty = function() { return this.count === 0; }; proto.containsKey = function(key) { if (this.isEmpty()) { return false; } for ( var prop in this.entrySet) { if (prop === key) { return true; } } return false; }; proto.containsValue = function(value) { if (this.isEmpty()) { return false; } for ( var key in this.entrySet) { if (this.entrySet[key] === value) { return true; } } return false; }; proto.get = function(key) { if (this.isEmpty()) { return null; } if (this.containsKey(key)) { return this.entrySet[key]; } return null; }; proto.put = function(key, value) { this.entrySet[key] = value; this.count++; }; proto.remove = function(key) { if (this.containsKey(key)) { delete this.entrySet[key]; this.count--; } }; proto.putAll = function(map) {
if(!map instanceof Map){
return;
}
for ( var key in map.entrySet) { this.put(key, map.entrySet[key]); } }; proto.clear = function() { for ( var key in this.entrySet) { this.remove(key); } }; proto.values = function() { var result = []; for ( var key in this.entrySet) { result.push(this.entrySet[key]); } return result; }; proto.keySet = function() { var result = []; for ( var key in this.entrySet) { result.push(key); } return result; }; proto.toString = function() { var result = []; for ( var key in this.entrySet) { result.push(key + ":" + this.entrySet[key]); } return "{" + result.join() + "}"; }; proto.valueOf = function() { return this.toString(); }; win.Map = Map; })(window);
我们写一个页面测试一下
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> <script type="text/javascript" src="Map.js"></script> <script type="text/javascript"> window.onload = function() { var map = new Map(); map.put("name", "jack"); map.put("age", "28"); map.put("gender", "male"); println(map.get("name")); println(map.isEmpty()); println(map.get("name")); println(map.size()); println(map.keySet()); println(map.values()); println(map.count); println(map); println("-----------------------------------------"); var map2 = new Map(); map2.putAll(map); println(map2); map2.remove("gender"); println(map2); println(map2.size()); println(map2.containsKey("name")); println(map2.containsValue("jack")); map2.clear(); println(map2); println(map2.size()); println(map2.containsKey("name")); println(map2.containsValue("jack")); } </script> </head> <body> </body> </html>
输出结果如下:
jack
false
jack
3
[name,age,gender]
[jack,28,male]
3
{name:jack,age:28,gender:male}
-----------------------------------------
{name:jack,age:28,gender:male}
{name:jack,age:28}
2
true
true
{}
0
false
false