Reputation: 1919
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?
Upvotes: 3
Views: 2983
Reputation: 781868
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));
Upvotes: 5
Reputation: 2614
From MDN
Iterable is an Array or other iterable object whose elements are key-value pairs (2-element Arrays).
And
The keys must be objects and the values can be arbitrary values.
So:
var o = {a:1};
var arr = [[o, 10]];
var wm1 = new WeakMap(arr);
Upvotes: 0
Reputation: 138457
You need a 2D array, like [[key1, value1], [key2, value2]]
. As you don't have keys a WeakSet would be more appropriate here.
Upvotes: 3