本文主要是介绍javascript中的WeakMap和WeakSet,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
WeakMap的key不能是基本类型
let weakMap = new WeakMap();let obj = {};weakMap.set(obj, "ok"); // works fine (object key)// can't use a string as the key
weakMap.set("test", "Whoops"); // Error, because "test" is not an object
如果key指向了null,则key会被自动回收
let john = { name: "John" };let weakMap = new WeakMap();
weakMap.set(john, "...");john = null; // overwrite the reference// john is removed from memory!
WeekMap只有如下的方法
- weakMap.get(key)
- weakMap.set(key, value)
- weakMap.delete(key)
- weakMap.has(key)
什么时候使用这个数据结构,如果key失去了引用,那么就自动回收它,比如用户和用户的访问量,如果用户离开了,那么它的访问量也就没有存在的价值了,此时可以使用这个数据结构进行存储
let visitsCountMap = new WeakMap(); // weakmap: user => visits count// increase the visits count
function countUser(user) {let count = visitsCountMap.get(user) || 0;visitsCountMap.set(user, count + 1);
}
另外一种用途就是缓存
let cache = new WeakMap();// calculate and remember the result
function process(obj) {if (!cache.has(obj)) {let result = /* calculate the result for */ obj;cache.set(obj, result);}return cache.get(obj);
}// 📁 main.js
let obj = {/* some object */};let result1 = process(obj);
let result2 = process(obj);// ...later, when the object is not needed any more:
obj = null;// Can't get cache.size, as it's a WeakMap,
// but it's 0 or soon be 0
// When obj gets garbage collected, cached data will be removed as well
WeakSet可以用来记录哪些人访问了网站
let visitedSet = new WeakSet();let john = { name: "John" };
let pete = { name: "Pete" };
let mary = { name: "Mary" };visitedSet.add(john); // John visited us
visitedSet.add(pete); // Then Pete
visitedSet.add(john); // John again// visitedSet has 2 users now// check if John visited?
alert(visitedSet.has(john)); // true// check if Mary visited?
alert(visitedSet.has(mary)); // falsejohn = null;// visitedSet will be cleaned automatically
这篇关于javascript中的WeakMap和WeakSet的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!