Is there any kind of hash code function in JavaScript?

后端 未结 20 1213
慢半拍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:31

    JavaScript objects can only use strings as keys (anything else is converted to a string).

    You could, alternatively, maintain an array which indexes the objects in question, and use its index string as a reference to the object. Something like this:

    var ObjectReference = [];
    ObjectReference.push(obj);
    
    set['ObjectReference.' + ObjectReference.indexOf(obj)] = true;
    

    Obviously it's a little verbose, but you could write a couple of methods that handle it and get and set all willy nilly.

    Edit:

    Your guess is fact -- this is defined behaviour in JavaScript -- specifically a toString conversion occurs meaning that you can can define your own toString function on the object that will be used as the property name. - olliej

    This brings up another interesting point; you can define a toString method on the objects you want to hash, and that can form their hash identifier.

提交回复
热议问题