3

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?

Penny Liu
  • 15,447
  • 5
  • 79
  • 98
krave
  • 1,629
  • 4
  • 17
  • 36
  • The weakmap constructor takes an iterable of *key-value pairs*, i.e. two-element arrays. – Bergi Jul 25 '18 at 09:26

3 Answers3

5

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));
Barmar
  • 741,623
  • 53
  • 500
  • 612
3

You need a 2D array, like [[key1, value1], [key2, value2]]. As you don't have keys a WeakSet would be more appropriate here.

Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151
0

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);
pishpish
  • 2,574
  • 15
  • 22