Javascript HashTable use Object key

后端 未结 11 1233
误落风尘
误落风尘 2020-12-13 17:29

I want to create a hash table with Object keys that are not converted into String.

Some thing like this:

var object1 = new Object();
var o         


        
11条回答
  •  失恋的感觉
    2020-12-13 18:17

    I took @Florian Margaine's suggestion to higher level and came up with this:

    function HashTable(){
        var hash = new Object();
        this.put = function(key, value){
            if(typeof key === "string"){
                hash[key] = value;
            }
            else{
                if(key._hashtableUniqueId == undefined){
                    key._hashtableUniqueId = UniqueId.prototype.generateId();
                }
                hash[key._hashtableUniqueId] = value;
            }
    
        };
    
        this.get = function(key){
            if(typeof key === "string"){
                return hash[key];
            }
            if(key._hashtableUniqueId == undefined){
                return undefined;
            }
            return hash[key._hashtableUniqueId];
        };
    }
    
    function UniqueId(){
    
    }
    
    UniqueId.prototype._id = 0;
    UniqueId.prototype.generateId = function(){
        return (++UniqueId.prototype._id).toString();
    };
    

    Usage

    var map = new HashTable();
    var object1 = new Object();
    map.put(object1, "Cocakola");
    alert(map.get(object1)); // Cocakola
    
    //Overriding
    map.put(object1, "Cocakola 2");
    alert(map.get(object1)); // Cocakola 2
    
    // String key is used as String     
    map.put("myKey", "MyValue");
    alert(map.get("myKey")); // MyValue
    alert(map.get("my".concat("Key"))); // MyValue
    
    // Invalid keys 
    alert(map.get("unknownKey")); // undefined
    alert(map.get(new Object())); // undefined
    

提交回复
热议问题