1. 程式人生 > 其它 >JavaScript 簡單實現的Map

JavaScript 簡單實現的Map

2019獨角獸企業重金招聘Python工程師標準>>> hot3.png

使用方法

Map.put(key,value);
Map.get(key);
Map.remove(key); 

Map.eachMap(function(key,value){
    document.write(key+"-->"+value+"<br>");
});
/**
 * Map
 */
(function(W, $) {
    function Map(){
        //私有變數
        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 是javascript中關鍵字 作用是刪除類中的一些屬性
            delete arr[key]
        }
        //遍歷
        this.eachMap = function(fn){
            for(var key in arr){
                fn(key,arr[key])
            }
        }
    }
    /*var country = new jMap();
    country.put("01","ZG");
    country.put("02","HG");
    country.put("03","MG");
    country.put("04","TG");
    //alert(country.get("01"))
    country.remove("01")
    //alert(country.get("01"))

    country.eachMap(function(key,value){
        document.write(key+"-->"+value+"<br>");
    })*/
    W['Map'] = new Map();
})(window, jQuery);

轉載於:https://my.oschina.net/kdy1994/blog/1829359