Is there any kind of hash code function in JavaScript?

后端 未结 20 1200
慢半拍i
慢半拍i 2020-12-04 09:59

Basically, I\'m trying to create an object of unique objects, a set. I had the brilliant idea of just using a JavaScript object with objects for the property names. Such as,

20条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-04 10:35

    The easiest way to do this is to give each of your objects its own unique toString method:

    (function() {
        var id = 0;
    
        /*global MyObject */
        MyObject = function() {
            this.objectId = '<#MyObject:' + (id++) + '>';
            this.toString= function() {
                return this.objectId;
            };
        };
    })();
    

    I had the same problem and this solved it perfectly for me with minimal fuss, and was a lot easier that re-implementing some fatty Java style Hashtable and adding equals() and hashCode() to your object classes. Just make sure that you don't also stick a string '<#MyObject:12> into your hash or it will wipe out the entry for your exiting object with that id.

    Now all my hashes are totally chill. I also just posted a blog entry a few days ago about this exact topic.

提交回复
热议问题