用js模仿java裡的Map,存入,獲取,大小,遍歷,移除
阿新 • • 發佈:2019-01-04
<script type="text/javascript"> function Map(){ var obj = {}; //put方法 this.put = function(key,value){ obj[key] = value; } //物件大小 this.size = function(){ var num = 0; for(var arr in b=obj){ num++; } return num; } //通過key獲得值 this.get = function(key){ if (obj[key] || obj[key] === 0 || obj[key] == false) { return obj[key]; }else{ return null; } } //移除key this.remove = function(key){ delete obj[key]; } //遍歷物件裡的key this.eachMap = function(fn){ for(var arr in obj){ fn(arr,obj[arr]); } } } //模仿java裡的Map var m = new Map(); m.put('01','哈哈'); m.put('02',123); m.put('03',true); console.log(m.size()); console.log(m.get('03')); console.log(m.remove('02')); m.eachMap(function(key,value){ console.log(key + " " + value); }); </script>