Set
- Set对象是值的集合,你可以按照插入的顺序迭代它的元素。 Set中的元素只会出现一次,即 Set 中的元素是唯一的。
let mySet = new Set() let obj = { a : 1, b : 2 } mySet.add(obj) mySet.add({ a : 1, b : 2 }) //虽然与 obj 字面量相同,但是内存地址不同 mySet.add(1) mySet.add(1) mySet.add(null) mySet.add(NaN) mySet.add(NaN) console.log(mySet.size) console.log(mySet.has(1)) console.log(mySet.has(null)) console.log(mySet.has(3)) console.log('删除:' + mySet.delete(NaN)) console.log(mySet) mySet.clear() console.log(mySet) /* 5 true true false 删除:true Set { { a: 1, b: 2 }, { a: 1, b: 2 }, 1, null } Set {} */
- 方法
- 将
Array
转换成Set
实现数组去重
const arr = [1,1,2,3,4,5,2,6,4,5,6] const mySet = new Set(arr) console.log(mySet)
- 将
Set
转换成Array
,即可使用数组方法
[...mySet].reverse()
forEach()
遍历
mySet.forEach((value, index, arr) => { console.log(value, index, arr) })
- 求交集
function getIntersection(arr1, arr2) { const set1 = new Set(arr1) const set2 = new Set(arr2) return [...set1].filter(item => set2.has(item)) }
- 求差集
function getDifference(arr1, arr2) { const set1 = new Set(arr1) const set2 = new Set(arr2) return [...set1].filter(item => !set2.has(item)) }
- 判断是否是子集
function isSuperset(arr1, arr2) { const set = new Set(arr1) const subset = new Set(arr2) for (let elem of subset) { if (!set.has(elem)) { return false; } } return true; }
- 求合集
function getUnion(arr1, arr2){ const union = new Set(arr1) arr2.map(item => union.add(item)) return [...union]
- 字符串相关
- 大小写敏感
console.log(new Set('hello zEd!')) console.log(new Set('hello zed!')) // Set { 'h', 'e', 'l', 'o', ' ', 'z', 'E', 'd', '!' } // Set { 'h', 'e', 'l', 'o', ' ', 'z', 'd', '!' }
- 将
Set 集合
最新推荐文章于 2022-06-29 16:50:15 发布