What's the difference between ES6 Map and WeakMap?

前端 未结 7 655
感情败类
感情败类 2020-12-02 06:00

Looking this and this MDN pages it seems like the only difference between Maps and WeakMaps is a missing \"size\" property for WeakMaps. But is this true? What\'s the differ

相关标签:
7条回答
  • 2020-12-02 06:51

    Another difference (source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakMap):

    Keys of WeakMaps are of the type Object only. Primitive data types as keys are not allowed (e.g. a Symbol can't be a WeakMap key).

    Nor can a string, number, or boolean be used as a WeakMap key. A Map can use primitive values for keys.

    w = new WeakMap;
    w.set('a', 'b'); // Uncaught TypeError: Invalid value used as weak map key
    
    m = new Map
    m.set('a', 'b'); // Works
    
    0 讨论(0)
提交回复
热议问题