一、Set的使用
Set
是ES6
中新增的一个数据结构,也就是集合。其中该数据结构中存在一些方法,可以帮助我们更快的解决数组中的问题。
1、set类型必须存放可迭代数据类型
2、Set可以用来去重
3、Set具有如下方法, add, delete, clear, has, forEach, 以及size属性,Set也支持for--of迭代的
//add方法
const s1 = new Set([1,2,3,4,5,2])
s1.add(111)
console.log(s1) //{1,2,3,4,5,111}
//delete方法
const s1 = new Set([1, 2, 3, 4, 5, 2])
s1.delete(5)
console.log(s1) //{1,2,3,4}
//has方法
const s1 = new Set([1, 2, 3, 4, 5, 2])
console.log(s1.has(5)) //true
//clear方法
const s1 = new Set([1, 2, 3, 4, 5, 2])
s1.clear()
console.log(s1) //{}
//size属性
const s1 = new Set([1, 2, 3, 4, 5, 2])
console.log(s1.size) // 5
//for--each
const s1 = new Set([1, 2, 3, 4, 5, 2])
s1.forEach(item => {
console.log(item) //1,2,3,4,5
})
//for--of
const s1 = new Set([1, 2, 3, 4, 5, 2])
for(let i of s1) {
console.log(i) //1,2,3,4,5
}
二、weakset类型
2.1、基本使用
const ws1 = new WeakSet()
const obj = {
name: 'sss'
}
ws1.add(obj)
console.log(ws1.has(obj)) //true
2.2、WeakSet中只能存放对象类型的数据
const ws1 = new WeakSet()
const obj = "t"
ws1.add(obj)
console.log(ws1.has(obj)) //报错
2.3、WeakSet中存在方法:add, delete, has
const ws1 = new WeakSet()
const obj = {
name: 'sss'
}
ws1.add(obj)
console.log(ws1.has(obj)) //true
ws1.delete(obj)
console.log(ws1.has(obj)) //false
2.4、WeakSet对其中的对象的引用是弱引用类型,也就是说其中宁的对象在没有任何其他引用的情况下,会进行垃圾回收。
2.5、由于WeakSet是弱引用类型,其中的元素个数不能确定,所以无法进行循环遍历。
2.6、stack overflow给出的WeakSet的用途
const ws = new WeakSet()
class Person {
constructor() {
ws.add(this)
}
running() {
if (!ws.has(this)) {
throw new Error('不能改变this的执行来执行running方法')
} else {
console.log('执行running方法')
}
}
}
let p = new Person()
p.running()
p.running.call({name: 'zs'}) //报错
如上述代码所示,当我们在进行初始化时,就将该实例话对象放入WeakSet
中,当我们执行running
函数时,如果当前实例化对象不存在时,则就会报错。