WeakMap和Map使用上类似,在特性上和Set类似,和Map相比,有一下特点
不可枚举
WeakMap的key只能是对象
WeakMap是弱引用,WeakMap内的key如果没有引用,将会被垃圾回收机制回收
new WeakMap([[{},1]])
let weakmap=new WeakMap() weakmap.add({},"1") weakmap.add({num:1},()=>{})
let obj={} let weakmap=new WeakMap() weakmap.add(obj,"1") weakmap.add({},"2") weakmap.delete(obj) //true weakmap.delete({}) //false
let obj={} let weakmap=new WeakMap() weakmap.add(obj,"1") weakmap.has(obj)//true weakmap.has({})//false
let weakmap=new WeakMap([[{},1]]) setTimeout(()=>{console.log(weakmap)},3000) // 3s后输出一下内容,数据消失了 WeakMap {}