- 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.
推薦閱讀
- Spring Cloud Alibaba微服務架構(gòu)設計與開發(fā)實戰(zhàn)
- Mastering OpenCV Android Application Programming
- SQL語言從入門到精通
- SQL Server從入門到精通(第3版)
- 速學Python:程序設計從入門到進階
- Mastering React
- 深度學習原理與PyTorch實戰(zhàn)(第2版)
- Visual Basic程序設計(第三版)
- 從零開始學UI:概念解析、實戰(zhàn)提高、突破規(guī)則
- Software-Defined Networking with OpenFlow(Second Edition)
- jQuery Mobile Web Development Essentials(Second Edition)
- Kotlin入門與實戰(zhàn)
- Swift編程實戰(zhàn):iOS應用開發(fā)實例及完整解決方案
- 谷歌JAX深度學習從零開始學
- Python3從入門到實戰(zhàn)