admin管理员组

文章数量:1388046

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?

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?

Share Improve this question edited Jul 25, 2018 at 10:20 Penny Liu 17.6k5 gold badges86 silver badges108 bronze badges asked Jul 25, 2018 at 9:20 kravekrave 1,9196 gold badges22 silver badges42 bronze badges 1
  • The weakmap constructor takes an iterable of key-value pairs, i.e. two-element arrays. – Bergi Commented Jul 25, 2018 at 9:26
Add a ment  | 

3 Answers 3

Reset to default 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));

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

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

本文标签: javascriptHow to new WeakMap with array as parameterStack Overflow