Is there any kind of hash code function in JavaScript?

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

    What you described is covered by Harmony WeakMaps, part of the ECMAScript 6 specification (next version of JavaScript). That is: a set where the keys can be anything (including undefined) and is non-enumerable.

    This means it's impossible to get a reference to a value unless you have a direct reference to the key (any object!) that links to it. It's important for a bunch of engine implementation reasons relating to efficiency and garbage collection, but it's also super cool for in that it allows for new semantics like revokable access permissions and passing data without exposing the data sender.

    From MDN:

    var wm1 = new WeakMap(),
        wm2 = new WeakMap();
    var o1 = {},
        o2 = function(){},
        o3 = window;
    
    wm1.set(o1, 37);
    wm1.set(o2, "azerty");
    wm2.set(o1, o2); // A value can be anything, including an object or a function.
    wm2.set(o3, undefined);
    wm2.set(wm1, wm2); // Keys and values can be any objects. Even WeakMaps!
    
    wm1.get(o2); // "azerty"
    wm2.get(o2); // Undefined, because there is no value for o2 on wm2.
    wm2.get(o3); // Undefined, because that is the set value.
    
    wm1.has(o2); // True
    wm2.has(o2); // False
    wm2.has(o3); // True (even if the value itself is 'undefined').
    
    wm1.has(o1);   // True
    wm1.delete(o1);
    wm1.has(o1);   // False
    

    WeakMaps are available in current Firefox, Chrome and Edge. They're also supported in Node v7 , and in v6 with the --harmony-weak-maps flag.

提交回复
热议问题