Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to iterate over a weakmap?

A javascript WeakMap ( https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakMap ) does not allow you to get the key, or the length or size, by design.

Is it possible to nevertheless loop over entries in some way ?

If not .. how does the Chrome console do this ?

enter image description here

like image 419
commonpike Avatar asked Sep 04 '15 16:09

commonpike


People also ask

Why are WeakMap keys not enumerable?

A WeakMap can be a particularly useful construct when mapping keys to information about the key that is valuable only if the key has not been garbage collected. But because a WeakMap doesn't allow observing the liveness of its keys, its keys are not enumerable. There is no method to obtain a list of the keys.

When would you use a WeakMap?

Whenever you want to extend an object but can't because it is sealed - or from an external source - a WeakMap can be applied. A WeakMap is a map (dictionary) where the keys are weak - that is, if all references to the key are lost and there are no more references to the value - the value can be garbage collected.

What is the difference between MAP and WeakMap?

Differences between Map and WeakMap 1) A WeakMap accepts only objects as keys whereas a Map,in addition to objects, accepts primitive datatype such as strings, numbers etc. 2) WeakMap objects doesn't avert garbage collection if there are no references to the object which is acting like a key.


1 Answers

Is it possible to nevertheless loop over entries in some way?

No, as you say, the contents of a WeakMap are not accessible by design, and there is no iterability.

If not … how does the Chrome console do this?

The console uses the debugging API of the JS engine, which allows access to the internals of objects (also to promise states, wrapped primitives, etc.) and many more.

like image 103
Bergi Avatar answered Oct 18 '22 21:10

Bergi