How to iterate over a weakmap?

匿名 (未验证) 提交于 2019-12-03 08:39:56

问题:

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 ?

回答1:

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.



回答2:

You can use this small snippet for universal forEach. However it uses lodash and can be enhanced greatly.

import lodashForEach from 'lodash/forEach'; import entries from 'lodash/entries'; /**  * @since lodash@4.17.3  * @param {Array|Map|Object|Set|WeakMap|WeakSet} iterable  * @param {Function} iteratee  * @example  * const iterable = new Map();  * iterable.set('somekey1', 1);  * iterable.set('somekey2', 2);  * // or  * const iterable = new Set();  * iterable.add("entry1");  * iterable.add("entry2");  * // run function  * forEach(iterable, (value, key) => {  *   console.group('-');  *   console.info('KEY');  *   console.log(key);  *   console.info('VALUE');  *   console.log(value);  *   console.groupEnd();  * });  */ function forEach(iterable, iteratee) {     lodashForEach((iterable instanceof Set || iterable instanceof WeakSet) ? Array.from(iterable) : entries(iterable), (entry, index, collection) => {       iteratee(entry[1], entry[0], collection, index);     });     return iterable; }  export default forEach;

UPDATE

After long time passed I found this answer incorrect. The thing is older version of core-js polyfill library has fixed bug where it replaces native WeakMap implementation with its own. So my solution is not valid in modern browsers.

function forEach(iterable, iteratee) {     switch (true) {         case Array.isArray(iterable) || iterable instanceof Map:             iterable.forEach(iteratee);             break;         case iterable instanceof Set:             Array.from(iterable).forEach(iteratee);             break;         case iterable instanceof WeakMap || iterable instanceof WeakSet:             // some kind of warning             break;         default:             Object.keys(iterable).forEach((key) => iteratee.call(null, iterable[key], key));             break;     }     return iterable; }


转载请标明出处:How to iterate over a weakmap?
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!