- React工程师修炼指南
- 开课吧组编 高少云 莫涛 韩明洋 余维海编著
- 339字
- 2021-04-14 11:28:43
1.9 Set和Map集合
在ES5标准中通过对象及数组来表示数据。ES6标准中提供新的数据结构来表示数据,那就是Set和Map。Set集合,是一种无重复元素的列表,而Map集合是键值对的集合。
1.9.1 Set集合
ES6标准中提供Set构造函数来创建集合。通过add()方法向集合中添加元素,访问集合的size属性可以获取集合中目前的元素数量。代码如下:

同样可以通过delete()方法删除Set集合中的某一个元素,调用clear()方法移除集合中的所有元素,has方法判断是否有某个元素。代码如下:


一般可以通过set不可重复的属性来做去重的处理。例如将[1,2,3,3,4,5,2,6]数组中相同的元素去重,代码如下:

1.9.2 Map集合
Map类型是有键值对的集合,可以通过Map构造函数来创建。通过set()函数来添加键名和键值。如果想获取某个属性名可以通过get()方法,代码如下:

同样Map集合也支持has()、delete()、clear()方法。代码如下:
