15.Set集合

 

1.Set集合方法

ES6提供了新的数据结构Set,类似于数组,元素值为唯一的,不能重复,Set实现了iterator接口,可以使用...for of进行遍历

  1. new Set():构造方法,参数可以是数组,new Set([elem1, elem2])
  2. size属性:集合的元素个数
  3. add():增加一个新元素,返回当前集合
  4. delete():删除元素,返回 boolean 值
  5. has():检测集合中是否包含某个元素,返回 boolean 值
  6. clear():清空集合,返回 undefined
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>集合</title>
</head>
<body>
<script>
let s1 = new Set();
let s2 = new Set(["a", "b", "c", "a"]);

console.log(s1);
console.log(typeof s1);
console.log(s2);
// Set(0) {size: 0}
// 'object'
// Set(3) {'a', 'b', 'c'}

let size = s2.size;
console.log(size);
// 3

s2.add('d');
console.log(s2);
// Set(4) {'a', 'b', 'c', 'd'}

for (let letter of s2) {
console.log(letter);
}
/*
a
b
c
d
*/

s2.delete('b');
console.log(s2);
// Set(3) {'a', 'c', 'd'}

let has_a = s2.has('a');
console.log(has_a);
// true

s2.clear();
console.log(s2);
// Set(0) {size: 0}

</script>
</body>
</html>

2.Set常见操作

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Set 实践</title>
</head>
<body>
<script>
// 1.数组去重
let arr1 = [1, 2, 3, 4, 5, 4, 3, 2];
let set1 = new Set(arr1)
let arr1_s = [...set1];
console.log(arr1_s);
// (5) [1, 2, 3, 4, 5]

// 2.求数组的交集
let arr2 = [4, 5, 6, 5, 6];
let set2 = new Set(arr2);
let arr2_s = [...set2];
let arr_unite = arr1_s.filter(item => {
if(set2.has(item)) {
return true;
}
else {
return false;
}
})
console.log(arr_unite);
// (2) [4, 5]

// 3. 求数组的并集
let arr_concat = [...arr1, ...arr2];
let merge_set = new Set(arr_concat);
let arr_merge = [...merge_set];
console.log(arr_merge);
// (6) [1, 2, 3, 4, 5, 6]

// 4.求数组的差集
let arr_diff = arr1_s.filter((item) => {
// if (set2.has(item)) {
// return false;
// } else {
// return true;
// }
return !(set2.has(item));
})
console.log(arr_diff);
// (3) [1, 2, 3]

</script>
</body>

</html>