Javascript HashTable use Object key

后端 未结 11 1234
误落风尘
误落风尘 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:05

    Based on Peters answer, but with proper class design (not abusing closures), so the values are debuggable. Renamed from Map to ObjectMap, because Map is a builtin function. Also added the exists method:

    ObjectMap = function() {
        this.keys = [];
        this.values = [];
    }
    
    ObjectMap.prototype.set = function(key, value) {
        var index = this.keys.indexOf(key);
        if (index == -1) {
            this.keys.push(key);
            this.values.push(value);
        } else {
            this.values[index] = value;
        }
    }
    
    ObjectMap.prototype.get = function(key) {
        return this.values[ this.keys.indexOf(key) ];
    }
    
    ObjectMap.prototype.exists = function(key) {
        return this.keys.indexOf(key) != -1;
    }
    
    /*
        TestObject = function() {}
    
        testA = new TestObject()
        testB = new TestObject()
    
        om = new ObjectMap()
        om.set(testA, true)
        om.get(testB)
        om.exists(testB)
        om.exists(testA)
        om.exists(testB)
    */
    

提交回复
热议问题