js 实现JAVAMAP

来源:互联网 发布:手机淘宝可以交电费吗 编辑:程序博客网 时间:2024/04/28 11:08

由于之前实现的东西需要由JAVA转换为js,发现数据结构js中,没有现成的,所以需要使用js模拟下

忘记原型是在哪抄的了,不过使用中有bug,fix了,在此留个脚印

 

var Map=function(){    this.mapArr={};    this.arrlength=0;//假如有重复key,则不存入    this.put=function(key,value){        this.mapArr[key]=value;        this.arrlength=this.arrlength+1;    }    this.get=function(key){        return this.mapArr[key];    }//传入的参数必须为Map结构    this.putAll=function(map){        if(Map.isMap(map)){            var innermap=this;            map.each(function(key,value){                if(innermap.containsKey(key)){                    innermap.remove(key);                }                innermap.put(key,value);            })        }else{            alert("传入的非Map结构");        }    }    this.remove=function(key){        delete this.mapArr[key];        this.arrlength=this.arrlength-1;    }    this.size=function(){        return this.arrlength;    }//判断是否包含key    this.containsKey=function(key){        return (key in this.mapArr);    }//判断是否包含value    this.containsValue=function(value){        for(var p in this.mapArr){            if(this.mapArr[p]==value){                return true;            }        }        return false;    }//得到所有key 返回数组    this.keys=function(){        var keysArr=[];        for(var p in this.mapArr){            keysArr[keysArr.length]=p;        }        return keysArr;    }//得到所有value 返回数组    this.values=function(){        var valuesArr=[];        for(var p in this.mapArr){            valuesArr[valuesArr.length]=this.mapArr[p];        }        return valuesArr;    }    this.isEmpty=function(){        if(this.size()==0){            return false;        }        return true;    }    this.clear=function(){        this.mapArr={};        this.arrlength=0;    }//循环    this.each=function(callback){        for(var p in this.mapArr){            callback(p,this.mapArr[p]);        }    }}//判断是否是map对象Map.isMap=function(map){    return  (map instanceof Map);}//var map=new Map();//map.put("afei",25);//map.put("yaoming",31);//map.put("",321);//map.put("pp",2);//map.put("bill","55");//map.remove("afei");////    var map2=new Map();//map2.put("003",333);//map2.put("004",444);//map.putAll(map2);//////map.each(function(key,value){//    alert(key+" : "+value);//    });     


参考:http://duyunfei.iteye.com/blog/1102236

0 0
原创粉丝点击