Set
1 Set介绍
- Set用来创建一个集合
- 它的功能和数组类似,不同点在于Set中不能存储重复的数据
- Set存储元素是无序的,不能通过下标访问
2 创建Set
new Set()
:构造空Setnew Set([...])
:从数组构造
const set = new Set()
// 向set中添加数据
set.add(10)
set.add("孙悟空")
set.add(10)
console.log(set)
3 方法
size()
获取数量add()
添加元素has()
检查元素delete()
删除元素
4 遍历Set
方法一:for-of
const set = new Set()
// 向set中添加数据
set.add(10)
set.add("孙悟空")
set.add(10)
for (const item of set) {
console.log(item)
}
方法二:forEach
const set = new Set()
// 向set中添加数据
set.add(10)
set.add("孙悟空")
set.add(10)
set.forEach(item => {
console.log(item)
})
5 利用Set对数组去重
const arr2 = [1, 2, 3, 2, 1, 3, 4, 5, 4, 6, 7, 7, 8, 9, 10]
const set2 = new Set(arr2)
console.log([...set2])