Set是新的引用型的数据结构 它类似于数组,但是成员的值都是唯一的,没有重复的值。
Set本身是一个构造函数,用来生成 Set 数据结构。
Set函数可以接受一个数组作为参数,用来初始化。
重点:
const set = new Set([1, 2, 3, 4, 4]);
console.log(set); // Set(4) {1, 2, 3, 4}
先想一想 以前怎么判断是数组还是对象的?instanceof或者Object.prototype.toString.call(set)
let arr = [1,2,3];
let obj = {
a:1
}
console.log( arr instanceof Array);//true
console.log( obj instanceof Object);//true
console.log( Object.prototype.toString.call(arr));//[object Array]
console.log( Object.prototype.toString.call(obj));//[object Object]
let set = new Set([1,2,3,4]);
console.log( set instanceof Set);//true
console.log( Set.prototype.toString.call(set));//[object Set]
let set = new Set([1,2,3,4]);
let arr1 = Array.from(set);
let arr2 = [...set];
console.log(arr1,arr2);//(4) [1, 2, 3, 4]
let set = new Set();
let a = 5;
let b = '5';
set.add(a);
set.add(b);
console.log(Array.from(set))// [5, '5']
let set = new Set();
set.add({});
set.add({});
console.log(...set);// 此时有两项 {} {}
let arr1 = [1, 2, 3]
let arr2 = [4, 3, 2]
// 实现交集
console.log(new Set([...arr1, ...arr2]));//{1, 2, 3, 4}
let c = new Set([...arr1, ...arr2]);
let a = new Set(arr1); // 1,2,3
let b = new Set(arr2); //4, 3, 2
// 实现并集(has()方法和filter()方法结合)
console.log(new Set([...a].filter(a => b.has(a))));//{2, 3}
// 实现差集(a对于b的差集和b对于a的差集不一样)
console.log(new Set([...a].filter(item => !b.has(item))));// 1
console.log(new Set([...b].filter(item => !a.has(item))));// 4