11set数据结构-es6
# set数据结构
# 一、创建set数据结构
console.log(new Set([1,2,3,3,1,5]))//{1,2,3,5}
console.log(new Set(["a","c","a","b","b"]))//{'a', 'c', 'b'}
//如果是数组对象,对象不会进行去重
console.log(
new Set([
{ name: "小明", age: 18 },
{ name: "小红", age: 19, sex: "女" },
{ name: "小蓝", sex: "男" },
])
);
//去重
let arr = [1,2,3,1,2]
console.log([...new Set(arr)])//(new Set(arr)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# set数据结构操作
//add(value) 添加某个值,返回Set结构本身
let s = new Set([1,2,3])
let newS = s.add(4)
console.log(s)//{1, 2, 3, 4}
console.log(newS)//{1, 2, 3, 4}
//delete(value) 删除某个值,返回一个布尔值,表示删除是否成功
let s = new Set([1,2,3])
let newS = s.delete(3)
console.log(s)//{1,2}
console.log(newS)//true
//has(value) 返回一个布尔值,表示该值是否为Set的成员
let s = new Set([1,2,3])
let newS = s.has(1)
console.log(newS)//true
//clear() 清除所有成员,没有返回值
let s = new Set([1,2,3])
let newS = s.clear()
console.log(s)//{}
console.log(newS)//undefined
//Array.from 和 [...] 把set数据结构转成数组结构
let s = new Set([1,2,3])
console.log(Array.from(s))//[1, 2, 3]
console.log([...s])//[1, 2, 3]
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
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
编辑 (opens new window)
上次更新: 2022/04/24, 13:33:34