javascriptweakmap

How to new WeakMap with array as parameter?


I have been reading MDN docs about WeakMap. And it mentions the syntax:

new WeakMap([iterable])

But when I tried this, error occurred:

var arr = [{a:1}];
var wm1 = new WeakMap(arr);

Uncaught TypeError: Invalid value used as weak map key

Could you please offer me an example about how to do it via an array?


Solution

  • The documentation says:

    Iterable is an Array or other iterable object whose elements are key-value pairs (2-element Arrays).

    {a: 1} is an object, not a 2-element array.

    Further down it says:

    Keys of WeakMaps are of the type Object only.

    So you can't use a string as a key in a WeakMap.

    Try:

    var obj = {a:1};
    var arr = [[obj, 1]];
    var wm1 = new WeakMap(arr);
    console.log(wm1.has(obj));