1. Set方法使用
方法 | 描述 |
---|---|
add | 添加某个值,返回Set对象本身。 |
clear | 删除所有的键/值对,没有返回值。 |
delete | 删除某个键,返回true。如果删除失败,返回false。 |
forEach | 对每个元素执行指定操作。 |
has | 返回一个布尔值,表示某个键是否在当前 Set 对象之中。 |
2. new Set()
new Set()本质,将数组/字符串转化为对象,且去重
// 数组转对象且去重
let arr = [1,2,3,3,1,4];
let arrToObj = new Set(arr);
console.log("arrToObj",arrToObj);//{ 1, 2, 3, 4 }
// 字符串转对象且去重
let strToObj = new Set("ababbc");
console.log("strToObj",strToObj);//{ 'a', 'b', 'c' }
3. ...new Set()
去重并转化为数组输出
//数组去重,生成新数组
let noDouble = [...new Set(arr)];
console.log("noDouble",noDouble)// [1, 2, 3, 4]
//字符串去重 且转化为字符串
let str = [...new Set('ababbc')]; // "abc" 字符串去重
console.log("str",str)//abc
4.特殊操作
4.1 数组并集
let array1 = new Set([1, 2, 3]);
let array2 = new Set([4, 3, 2]);
let unionObj = new Set([...array1, ...array2]); // {1, 2, 3, 4}
console.log("unionObj",unionObj)
let unionArray = [...new Set([...array1, ...array2])]; // [ 1, 2, 3, 4 ]
console.log("unionArray",unionArray)
4.2 数组交集
let array1 = new Set([1, 2, 3]);
let array2 = new Set([4, 3, 2]);
let intersectionObj = new Set([...array1].filter(x => array2.has(x))); // { 2, 3 }
console.log("intersectionObj",intersectionObj)
let intersectionArray = [...new Set([...array1].filter(x => array2.has(x)))]; // [ 2, 3 ]
console.log("intersectionArray",intersectionArray)
4.3 数组差集
let array1 = new Set([1, 2, 3]);
let array2 = new Set([4, 3, 2]);
let diffObj = new Set([...array1].filter(x => !array2.has(x))); // { 1 }
console.log("diffObj",diffObj)
let diffArray = [...new Set([...array1].filter(x => !array2.has(x)))]; // [ 1 ]
console.log("diffArray",diffArray)