Set
对象允许你存储任何类
用于存储任何类型的唯一值,无论是基本类型还是对象引用。
-
只能保存值没有键名
-
严格类型检测如字符串数字不等于数值型数字
-
值是唯一的
-
遍历顺序是添加的顺序,方便保存回调函数
声明
里面以数组赋予
<script>
const set = new Set("bushigemen")
console.log(set)//Set(9) {'b', 'u', 's', 'h', 'i', …}
const set1 = new Set([1, 2, 3, 4, 5])
console.log(set1)//Set(5) {1, 2, 3, 4, 5}
const set2 = new Set(["ew", "set"])
console.log(set2)//Set(2) {'ew', 'set'}
//
const set3 = new Set('f')
console.log(set3)//Set(1) {'f'}
const set4 = new Set(1)
console.log(set4)//TypeError: number 1 is not iterable (cannot read property Symbol(Symbol.iterator)),错误
const obj = {
1: 222,
2: 111
}
const set5 = new Set(obj)
console.log(set5)//错误
const arr = [1, 2, 3]
const set6 = new Set(arr)
console.log(set6)//Set(3) {1, 2, 3}
</script>
方法:
1.获取元素数量
let hd = new Set();
hd.add('ad');
console.log(hd.has('ad'));//true
2.检测元素
let set = new Set(['as', 'df']);
console.log(hd.size); //2
3.添加
let hd = new Set();
hd.add('ad');
4.删除
1. 使用 delete
方法删除单个元素,返回值为boolean
类型
2. 使用 clear
删除所有元素
let hd = new Set();
hd.add("ad");
hd.add("df");
console.log(hd.delete("ad")); //true
hd.clear();