ES6 Map 和 WeakMap 有什么区别? [英] What's the difference between ES6 Map and WeakMap?

查看:34
本文介绍了ES6 Map 和 WeakMap 有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个this MDN 页面似乎 Maps 和 WeakMaps 之间的唯一区别是 WeakMaps 缺少大小"属性.但这是真的吗?它们有什么区别?

Looking this and this MDN pages it seems like the only difference between Maps and WeakMaps is a missing "size" property for WeakMaps. But is this true? What's the difference between them?

推荐答案

来自 同样的页面,部分为什么地图?":

有经验的 JavaScript 程序员会注意到这个 API 可以在 JavaScript 中使用两个数组(一个用于键,一个用于值)由 4 个 API 方法共享.这样的实现将有两个主要的不便之处.第一个是 O(n) 搜索(n 是映射中的键数).第二个是内存泄漏问题.使用手动编写的映射,键数组将保留对关键对象,防止它们被垃圾收集.在本地WeakMaps,对关键对象的引用弱",这意味着他们不会阻止垃圾收集,以防万一对对象的其他引用.

The experienced JavaScript programmer will notice that this API could be implemented in JavaScript with two arrays (one for keys, one for values) shared by the 4 API methods. Such an implementation would have two main inconveniences. The first one is an O(n) search (n being the number of keys in the map). The second one is a memory leak issue. With manually written maps, the array of keys would keep references to key objects, preventing them from being garbage collected. In native WeakMaps, references to key objects are held "weakly", which means that they do not prevent garbage collection in case there would be no other reference to the object.

由于引用较弱,WeakMap 键不可枚举(即没有任何方法可以为您提供密钥列表).如果他们是该列表将取决于垃圾收集的状态,引入不确定性.

Because of references being weak, WeakMap keys are not enumerable (i.e. there is no method giving you a list of the keys). If they were, the list would depend on the state of garbage collection, introducing non-determinism.

[这就是为什么它们也没有 size 属性]

[And that's why they have no size property as well]

如果你想要一个键列表,你应该自己维护.还有一个 ECMAScript提案旨在引入不会使用弱的简单集合和映射引用并且将是可枚举的.

If you want to have a list of keys, you should maintain it yourself. There is also an ECMAScript proposal aiming at introducing simple sets and maps which would not use weak references and would be enumerable.

- 这将是 "normal" Maps.MDN 上没有提到,但在 和谐提案 中,那些也有 itemskeysvalues 生成器方法并实现 Iterator 接口.

‐ which would be the "normal" Maps. Not mentioned at MDN, but in the harmony proposal, those also have items, keys and values generator methods and implement the Iterator interface.

这篇关于ES6 Map 和 WeakMap 有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆