特点:
//创建一个集合
let set = new Set(['bob', 'lucy', 'john', 'bob', 'lucy']);
//将重复的元素去除了
console.log(set);//Set(3) {"bob", "lucy", "john"}
console.log(Array.from(set));//转换为真数组 (3) ["bob", "lucy", "john"]
console.log(Array.from(set)[1]);//lucy
// 数组扁平化、去重、排序
const arr = [[1, 3, 4], [2, 3], 2, [2, [3, 5]]]
console.log(arr.flat(Infinity)) // [1, 3, 4, 2, 3, 2, 2, 3, 5]
console.log(Array.from(new Set(arr.flat(Infinity))).sort((a, b) => a - b)) // [ 1, 2, 3, 4, 5 ]
{
let set=new Set(['bob','lucy','john']);
//类似于length
console.log(set.size);//3
}
{
let set=new Set(['bob','lucy','john']);
//添加元素(支持链式调用)
console.log(set.add('bob2').add('tom'));//Set(5) {"bob", "lucy", "john", "bob2", "tom"}
console.log(set);//Set(5) {"bob", "lucy", "john", "bob2", "tom"}
}
注意:在 Set 内部,两个 NaN 是等价的,而对象不等价
{
const set1 = new Set()
const a = NaN, b = NaN
set1.add(a).add(b)
console.log(set1.size) // 1
const set2 = new Set()
const c = {}, d = {}
set2.add(c).add(d)
console.log(set2.size) // 2
}
{
let set=new Set(['bob','lucy','john']);
//删除元素(不支持链式调用)
console.log(set.delete('bob'));//true
console.log(set);//Set(2) {"lucy", "john"}
}
{
let set=new Set(['bob','lucy','john']);
//判断集合有没有查找元素
console.log(set.has('bob'));//true
console.log(set.has('bob1'));//false
}
{
let set=new Set(['bob','lucy','john']);
//清除集合元素
console.log(set.clear());//undefined
console.log(set);//Set(0) {}
}
keys()
:返回键名values()
:返回键值entries()
:返回键值对forEach()
:使用回调函数遍历每个成员Set 的遍历顺序就是插入顺序,可以保证按序添加调用
{
let set=new Set(['bob','lucy','john']);
console.log(set.keys()); //SetIterator {"bob", "lucy", "john"}
console.log(set.values()); //SetIterator {"bob", "lucy", "john"}
console.log(set.entries()); //SetIterator {"bob", "lucy", "john"}
// Set
for(let index of set.keys()){
console.log(index); //bob; lucy; john
}
for(let elem of set.values()){
console.log(elem); //bob; lucy; john
}
for(let [index,elem] of set.entries()){
console.log(index, elem); //bob bob; lucy lucy; john john;
}
// Array
for(let index of ['bob','lucy','john'].keys()){
console.log(index); //0; 1; 2
}
for(let elem of ['bob','lucy','john'].values()){
console.log(elem); //bob; lucy; john
}
for(let [index,elem] of ['bob','lucy','john'].entries()){
console.log(index, elem); //0 "bob"; 1 "lucy"; 2 "john";
}
}
forEach
let set0=new Set([1,2,5,3,4,2]) // Set(5) {1, 2, 5, 3, 4}
set0.forEach((value,index)=>{console.log(value,index)}) // 1 1, 2 2, 5 5, 3 3, 4 4
用 Set 取并、交、差集
{
let a = new Set([1, 2, 3]), b = new Set([4, 5, 6, 2])
// 并集
console.log(new Set([...a, ...b]))// Set(6) {1, 2, 3, 4, 5, …}
// 交集
console.log(new Set([...a].filter(x => b.has(x))))// Set(1) {2}
// 差集
console.log(new Set([...a].filter(x => !b.has(x))))// Set(2) {1, 3}
}
同 Set 类似(属性方法也类似),也是不重复值的集合,但是有两个区别:
{
let a = [[1, 2], [5, 6]]
let weak_set = new WeakSet(a)
console.log(weak_set) // WeakSet {Array(2), Array(2)}
}
注意:成为 WeakSet 的成员是 a 数组的成员,而不是 a 数组本身,这意味着,数组的成员只能是对象