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
3 Answers
Reset to default 5The 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
版权声明:本文标题:javascript - How to new WeakMap with array as parameter? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744510555a2609855.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论