es6入门Set数据结构详解
set
定义:
是一种新的数据结构,类似数组,其成员是唯一的,没有重复的值.
Set 结构没有键名,只有键值(或者说键名和键值是同一个值).
Set本身 是一个构造函数,用来生成set 数据结构
Set数据结构的原型方法有:

Set结构的实例有以下属性和方法:
属性:
Set.prototype.contructor: Set的构造函数
Set prototype.size:Set实例的成员总数
操作方法:
add(value) : 添加成员,返回Set结构本身
delete(value): 删除成员,返回布尔值,表示是否删除
has(value): 判断是否包含某成员,返回布尔值,表示结果
clear(): 清除成员,没有返回值
遍历方法:
keys() : 返回键名的遍历器对象
values(): 返回键值的遍历器对象
entries(): 返回键值对的遍历器对象
forEach(): 使用回调函数遍历成员
Set结构使用:
1、生成Set数据结构
Set构造函数的参数可以是一个数组(或者具有 iterable 接口的其他数据结构)
(1)生成空的数据结构
const s = new Set()

打印结果:

可以看到Set结构有一些方法可以调用,类似数组。上述就是一个Set构造函数的实例。
(2)接受一个数组作为参数(初始化)
const s = new Set([1,2,3])

打印结果:

经过初始化,Set有了初始化的成员,可以解构成一个数组。
注意,如果用来初始化的参数中有重复的值,Set会将它们去重:

打印结果:

故此,可以使用Set来给数组去重:

打印结果:

类似的,也可以使用Set给字符串去重:

打印结果:

2、在Set数据结构增加成员
s,add(value)

打印结果:

add方法每次添加一个成员,不会对添加的成员进行类型转换,可以链式添加成员。
当添加的值为String、Number、Boolean时,不可添加重复的成员,其判断成员是否唯一的算法类似于精确相等运算符(===)。
与“===”的区别:
NaN === NaN 为true,而Set结构把重复添加的NaN 视为一个值:

打印结果:

故此undefined、null 也不可在Set结构中重复添加。
由于两个对象永远不相等,所以可以在Set结构中重复添加同样的数组或者对象:

打印结果:

3、在Set结构中删除成员和清除成员
删除成员:
s.delete(value)

打印结果:

注意,delete方法没有办法删除对象和数组成员,使用时需注意。

打印结果:

清除所有成员:
s.clear();

打印结果:

4、判断Set结构是否包含某成员
s.has(value)

打印结果:

同样的,has方法也不能判断对象和数组成员是否在Set中。
5、取Set结构成员总数
s.size

6、获取Set结构的键值对
获取键名:
s.keys()

打印结果:

其返回的是一个编辑器对象。
获取键值:
s.values()

打印结果:

由于Set结构的键名和键值都一样,所以keys方法和values方法返回的结果是一样地。
返回键值对:
s.entries()

打印结果:

可以看到Set结构的键名和键值时相等的。
7、遍历Set结构
Set结构和数组一样,默认是可以遍历的,其默认遍历函数为values()。所以使用for循环对Set进行遍历时,可以获取每个键值:

打印结果:

故此,扩展运算符 “...”就可以运用在Set上了,因为扩展运算符是使用for循环对数据进行结构。
Set结构和数组一样,都有forEach函数,对每个成员用回调函数做一些操作,没有返回值。

打印结果:

forEach的回调函数有三个参数,分别是键值,键名,Set集合本身。
使用Set集合计算并集,交集和差集:

打印结果:

在遍历操作中改变Set结构的方法:

打印结果:

WeakSet
WeakSet有set大部分的特性,但是与Set有两个区别
1、成员只能是对象(数组是特殊的对象)
2、不可以被遍历,没有size属性,因为成员都是弱引用(不计入垃圾回收机制,垃圾回收机制自动回收该成员占用内存)
使用WeakSet可以防止内存泄漏,方便内存回收。