Set 实例的方法分为两大类:操作方法(用于操作数据)和遍历方法(用于遍历成员)。
它的唯一特性就是所有的元素都是唯一的,没有重复;可以使用该特性进行数组去重。
Set 实例的属性和方法
//add(value):添加某个值,返回 Set 结构本身。
//delete(value):删除某个值,返回一个布尔值,表示删除是否成功。
//has(value):返回一个布尔值,表示该值是否为Set的成员。
//clear():清除所有成员,没有返回值。
let list = new Set([1, 2, 2, 3]);
console.log(list); //{1,2,3}
console.log(typeof list); // object
console.log(Array.from(list)); // [1,2,3]Array.from 对象转为数组
// 1. 添加元素ass
let list1 = new Set();
list1.add = "1";
console.log(list1); //{1}
// 2. 删除元素
let list2 = new Set([5, 6, 7, 8]);
list2.delete(5); //直接放数组中元素的内容
console.log(list2); //{6,7,8}
// 3. 判断某元素是否存在 has
let list3 = new Set([7, 8, 9]);
console.log(list3.has(7)); // true
// 4. 清除所有的元素clear
let list4 = new Set([1, 2, 3]);
list4.clear();
console.log(list4); //Set(0) {}
注释: Array.from(list) 可以把set生成的对象,转为数组;
Set遍历操作
//Set 结构的实例有四个遍历方法,可以用于遍历成员。
//keys():返回键名的遍历器
//values():返回键值的遍历器
//entries():返回键值对的遍历器
//forEach():使用回调函数遍历每个成员
// 5.遍历 keys() 返回键名
let list5 = new Set(["a", "b", "c"]);
for(let i of list5.keys()){
console.log(i); // a, b, c
}
// 6. 遍历 values():返回键值
let list6 = new Set(["a", "b", "hello"]);
for(let j of list6.values()){
console.log(j); // a b hello
}
// 7.遍历 entries() 返回键值对
let list7 = new Set(["a", "b", "hello"]);
for(let k of list7.entries()){
console.log(k); //["a", "a"] ["b", "b"] ["hello", "hello"]
}
// 8. 遍历 forEach() 使用回调函数遍历每个成员
let list8 = new Set(["a", "b", "hello"]);
list8.forEach(v =>{
console.log(v); // a b hello
})