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

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

问题描述

查看这个 MDN页面,似乎Map和WeakMaps之间的唯一区别是WeakMaps的缺少size属性。但这是真的吗?他们之间有什么区别?

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?

推荐答案

相同的页面,为什么 Weak 映射?


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

由于引用不足,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.

[这就是为什么他们没有大小财产]

[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.

- 这将是< a href =https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Map =noreferrer>normal地图取值。在MDN中没有提及,但在和谐建议中,那些也有项目生成器方法并实现 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天全站免登陆