Is there any kind of hash code function in JavaScript?

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

    For my specific situation I only care about the equality of the object as far as keys and primitive values go. The solution that worked for me was converting the object to its JSON representation and using that as the hash. There are limitations such as order of key definition potentially being inconsistent; but like I said it worked for me because these objects were all being generated in one place.

    var hashtable = {};
    
    var myObject = {a:0,b:1,c:2};
    
    var hash = JSON.stringify(myObject);
    // '{"a":0,"b":1,"c":2}'
    
    hashtable[hash] = myObject;
    // {
    //   '{"a":0,"b":1,"c":2}': myObject
    // }
    

提交回复
热议问题