1 <!DOCTYPE html>
2 <html>
3 <head>
4 <meta charset="utf-8">
5 <title></title>
6 </head>
7 <body>
8 <script type="text/javascript">
9
10 // Set数据结构是es6新增的,类似于数组,可以用于数组的去重
11 let a = [1,1,2,3,3,4,4,5,6,6]
12 let b = new Set(a)
13 //此时虽然去重了,但是数据结构不是数组,需要将其转为数组方便下一步操作
14 console.log(b)
15 b.add(8) //添加一个元素,返回值为Set结构本身
16 b.delete(1) //删除某个值,返回值为布尔值,代表删除是否成功
17 b.has(2)//判断参数是否为Set成员,返回值为布尔值
18 //清空Set结构,无返回值
19 // b.clear()
20 b = [...b] //同样使用es6的扩展运算符将Set数据结构转为数组结构
21 console.log(b)
22 // 也可以这样 let b = [...new Set(a)]
23
24 let c = ['b','b','b','c','d']
25 let d = new Set(c)
26 // Set结构的遍历
27 for (let item of d.keys()) {
28 console.log(item) //key:b、c、d
29 }
30
31 for (let item of d.values()) { //此方法可直接省去 values()
32 console.log(item) //value: b、c、d
33 }
34
35 for (let item of d.entries()) {
36 console.log(item) //返回键值对:["b", "b"]["c", "c"]["d", "d"]
37 }
38
39 d.forEach((item,index,arr) => {
40 console.log(item,index,arr)
41 })
42 </script>
43 </body>
44 </html>