原文地址:https://www.cnblogs.com/douyaer/p/7942248.html
关于Set()函数
Set是一个构造器,类似于数组,但是元素没有重复的
1.接收数组或者其他iterable接口的数据 用于初始化数据
let a=new Set([1,32,424,22,12,3,2,2,1]);
console.log(a)//[ 1, 32, 424, 22, 12, 3, 2 ]
2. ☆实现数组去重
let b=[1,2,3,4,51,51,2,23,2];
let c=new Set(b);
b=[...c];
console.log(b);//[ 1, 2, 3, 4, 51, 23 ]
3. Set内默认NaN是相等的 遵循的是'==='
let d=new Set();
d.add(NaN);
d.add(NaN);
console.log(d);//[NaN]
4.Set()的方法
add()增加一个成员 返回set结构本身
delete()删除一个成员 返回bool
has()判断里面是否存在某个元素,返回bool
clear()清楚所有成员,没有返回值
let e=new Set();
let f=e.add(1);
console.log(e,f);//[1] [1]
let g=f.has(1);
console.log(g);//true
f.add(3);
console.log(f)//[1,3]
let h=f.delete(3);
console.log(h,f)//true [1]
f.clear();
console.log(f)//[]
5. Array.from()可以将set转换为数组
let i=new Set([1,2,3,4,5]);
console.log(Object.prototype.toString.call(Array.from(i)));//[object Array]
6.遍历方法 for...of
keys()
values()
entries()
forEach
let a=new Set([11,22,33,44]);
for(let i of a){
console.log(i)
}// 11 22 33 44
for(let i of a.values()){
console.log(i)
}//11 22 33 44
for(let i of a.keys()){
console.log(i)
}//11 22 33 44
for(let i of a.entries()){
console.log(i)
}//[11,11] [22,22] [33,33] [44,44]
a.forEach((key,value)=>{
console.log(key,value)
})//11 11 22 22 33 33 44 44
网友评论