Is there any kind of hash code function in JavaScript?

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

    In addition to eyelidlessness's answer, here is a function that returns a reproducible, unique ID for any object:

    var uniqueIdList = [];
    function getConstantUniqueIdFor(element) {
        // HACK, using a list results in O(n), but how do we hash e.g. a DOM node?
        if (uniqueIdList.indexOf(element) < 0) {
            uniqueIdList.push(element);
        }
        return uniqueIdList.indexOf(element);
    }
    

    As you can see it uses a list for look-up which is very inefficient, however that's the best I could find for now.

提交回复
热议问题