- 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核心技術(shù)與實(shí)戰(zhàn)案例
- TypeScript Blueprints
- Getting Started with ResearchKit
- vSphere High Performance Cookbook
- Django Design Patterns and Best Practices
- Spring Cloud、Nginx高并發(fā)核心編程
- QGIS By Example
- Java程序設(shè)計(jì)
- MATLAB for Machine Learning
- Photoshop CC移動(dòng)UI設(shè)計(jì)案例教程(全彩慕課版·第2版)
- Application Development with Parse using iOS SDK
- ASP.NET Core and Angular 2
- 產(chǎn)品架構(gòu)評(píng)估原理與方法
- 川哥教你Spring Boot 2實(shí)戰(zhàn)
- Cloud Development andDeployment with CloudBees