JS实现JAVA的Map

      Map接口在Java中经常使用,例如其实现类HashMap,而在JS里没有明确地实现此功能的元素(有功能类似的,如Object),使用“JS中排除重复元素”中的第2种方法,可以写一个简单的JS实现Map。

Map = function () {
    this.objects = new Object();
    
    // 加入元素
    this.put = function (key, value) {
        this.objects[key] = value;
    };
    
    // 删除元素
    this.remove = function (key) {
        this.objects[key] = undefined;
    };
    
    // 是否存在某键值
    this.containsKey = function (key) {
        return this.objects[key] ? true : false;
    };
    
    // 获取某元素
    this.get = function(key) {
        return this.objects[key];
    };
    
    // 是否存在某值
    this.containsValue = function (value) {
        for (var temp in this.objects) {
            if (this.objects[temp] == value) {
                return true;
            }
        }
        
        return false;
    };
    
    // 集合大小
    this.size = function () {
        var counter = 0;
        for (var temp in this.objects) {
            counter ++;
        }
        return counter;
    }
}
posted @ 2012-11-13 19:49  nick_huang  阅读(2003)  评论(0编辑  收藏  举报