Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 993
krave Avatar asked May 21 '26 08:05

krave


1 Answers

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));
like image 123
Barmar Avatar answered May 22 '26 21:05

Barmar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!