JavaScript hashmap equivalent

前端 未结 17 1438
执笔经年
执笔经年 2020-11-22 13:23

As made clear in update 3 on this answer, this notation:

var hash = {};
hash[X]

does not actually hash the object X; it actually

17条回答
  •  佛祖请我去吃肉
    2020-11-22 14:01

    In ECMAScript 6 you can use WeakMap.

    Example:

    var wm1 = new WeakMap(),
        wm2 = new WeakMap(),
        wm3 = 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')
    
    wm3.set(o1, 37);
    wm3.get(o1); // 37
    wm3.clear();
    wm3.get(o1); // Undefined, because wm3 was cleared and there is no value for o1 anymore
    
    wm1.has(o1);   // True
    wm1.delete(o1);
    wm1.has(o1);   // False
    

    But:

    Because of references being weak, WeakMap keys are not enumerable (i.e. there is no method giving you a list of the keys).

提交回复
热议问题