Set, Map, WeakSet和WeakMap这四种类型于ES6新增
Set和Map,类似于数组和对象
Set
集合由一组无序且唯一(即不重复)的项组成,相当于一个既没有重复元素,也没有顺序概念的数组
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| let set:Set<number> = new Set([1,1,4,5,1,4,1,9,1,9,8,1,0])
console.log(set)
console.log(set.size)
console.log(set.add(3)) console.log(set)
console.log(set.has(1))
console.log(set.delete(0)) console.log(set)
set.clear() console.log(set)
|
Map
1 2 3 4 5 6 7 8
|
let map:Map<object,any> = new Map() map.set({},"yjsp") map.set([],114) map.set(()=>{},514)
|
WeakSet和WeakMap
weakSet和weakMap的键都是弱引用,不会被计入垃圾回收
当键的引用数量为0时,就预示着它会被释放
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| let obj:any = {name:'yajue'} let jbo:any = obj
let wmap:WeakMap<object,string> = new WeakMap() wmap.set(obj,"yjsp") obj = null jbo = null
setTimeout(()=>{ console.log(wmap) },500)
|