JavaScript之JMap

在JavaScript中我们利用function类定义类
在类的内部我们用var 定义私有变量 私有函数
在类的内部我们用this 定义公有变量
(1)定义一个类
 function JMap() {
        var arr={};//空类
        //增加
        this.put=function (key,value) {//用一个方法将数据加到指定类中去
            arr[key]=value;
        }
        this.get=function (key) {
            if( arr[key]){
                return  arr[key];
            }else{
                return null;
            }
        }
        //删除
        this.remove=function (key) {
            delete  arr[key];
        }

        //遍历
        this.eachMap=function (fn) {
            for(var key in arr){
                fn(key,arr[key]);
            }
        }
    }

(2)使用 类(JMap类外部)


 var country=new JMap(); //实例化
    country.put("01","ZG");//添加值
    country.put("02","TG");
    country.put("03","MG");
 country.eachMap(function (key,value) {//回调函数
alert(key+" "+value+"<br>")
})


 
原文地址:https://www.cnblogs.com/wfaceboss/p/7636292.html