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?

1
  • The weakmap constructor takes an iterable of key-value pairs, i.e. two-element arrays. Commented Jul 25, 2018 at 9:26

3 Answers 3

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));

Sign up to request clarification or add additional context in comments.

Comments

3

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

Comments

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.