- Hands-On Data Structures and Algorithms with JavaScript
- Kashyap Mukkamala
- 171字
- 2021-06-30 19:12:17
Understanding WeakSets
WeakSet is very similar to WeakMap; the values that a WeakSet can hold are only objects and cannot be primitives just like in the case of a WeakMap. The WeakSets are also not enumerable, so you do not have direct access to the values available inside the set.
Let's create a small example and understand the difference between a Set and a WeakSet:
var set = new Set();
var wset = new WeakSet();
(function() {
var a = {a: 1};
var b = {b: 2};
var c = {c: 3};
var d = {d: 4};
set.add(1).add(2).add(3).add(4);
wset.add(a).add(b).add(b).add(d);
})();
console.dir(set);
console.dir(wset);
One important thing to note is that WeakSet does not accept primitives and can only accept objects similar to the WeakMap keys.
The output of the preceding code is as follows, which is what was expected from the WeakSet. WeakSet does not retain elements beyond the lifespan of the variables that were holding them:

As expected, the WeakSet is empty once the IIFE is terminated.
推薦閱讀
- C#高級編程(第10版) C# 6 & .NET Core 1.0 (.NET開發經典名著)
- React Native Cookbook
- Go語言精進之路:從新手到高手的編程思想、方法和技巧(2)
- Service Mesh實戰:基于Linkerd和Kubernetes的微服務實踐
- ServiceNow:Building Powerful Workflows
- Scratch3.0趣味編程動手玩:比賽訓練營
- Kubernetes源碼剖析
- Distributed Computing in Java 9
- Arduino電子設計實戰指南:零基礎篇
- Ext JS 4 Plugin and Extension Development
- Learning Image Processing with OpenCV
- Java并發實現原理:JDK源碼剖析
- Mastering PowerCLI
- JavaScript Concurrency
- 優化驅動的設計方法