JavaScriptはMapオブジェクトを作成します.

3689 ワード

function Map(){
    // private 
    var obj = {};//           ,     

    // put   
    this.put = function(key,value){
        obj[key] = value; //       obj   
    }

    // size   ,  map     
    this.size = function(){
        var count = 0;
        for(var attr in obj){
            count++;
        }
        return count;
    }

    // get      key   value
    this.get = function(key){
        if(obj[key]||obj[key]===0||obj[key]===false){
            return obj[key];
        }else{
            return null;
        }
    }

    // remove     
    this.remove = function(key){
        if(obj[key]||obj[key]===0||obj[key]===false){
            delete obj[key];
        }
    }

    // eachMap   map     (    )
    this.eachMap = function(fn){
        for(var attr in obj){
            fn(attr, obj[attr]);
        }
    }
}

//   java Map
var m = new Map();
m.put('01' , 'abc');
m.put('02' , false) ;
m.put('03' , true);
m.put('04' , new Date());

alert(m.size());
alert(m.get('02'));
m.remove('03');
alert(m.get('03'));

m.eachMap(function(key, value){
    alert(key+':'+value);
})