📜  JavaScript 中的 Map 和 WeakMap 有什么区别?

📅  最后修改于: 2022-05-13 01:56:15.022000             🧑  作者: Mango

JavaScript 中的 Map 和 WeakMap 有什么区别?

在本文中,我们将讨论 ES6 引入的 Map 和 WeakMap 的区别。 Javascript 对象只支持一个键对象。为了支持多个关键对象,那么 Map 就走上了这条路。

Map: Map 是键值对的无序列表,其中键和值可以是任何类型,如字符串、布尔值、数字等。为了更好地理解,我们以 Map 及其属性为例。

例子:

Javascript


Javascript


输出:

上述代码的输出(Map)

WeakMap:在 Weak Map 中,每个键只能是对象和函数。它用于存储弱对象引用。为了更好地理解,我们以 WeakMap 及其属性为例:

例子:

Javascript


输出:

上述代码的输出(WeakMap)

Map和WeakMap的区别:

Map

WeakMap

A Map is an unordered list of key-value pairs where the key and the value can be of any type like string, boolean, number, etc.In a Weak Map, every key can only be an object and function. It used to store weak object references.
Maps are iterable.WeakMaps are not iterable.
Maps will keep everything even if you don’t use them.WeakMaps holds the reference to the key, not the key itself.
The garbage collector doesn’t remove a key pointer from “Map” and also doesn’t remove the key from memory.The garbage collector goes ahead and removes the key pointer from “WeakMap” and also removes the key from memory. WeakMap allows the garbage collector to do its task but not the Map.
Maps have some properties : .set, .get, .delete, .size, .has, .forEach, Iterators.WeakMaps have some properties : .set, .get, .delete, .has.
You can create a new map by using a new Map().You can create a new WeakMap by using a new WeakMap().