汇合

简直每种变成语言中,都有汇合构造。汇合通常是由一组无序的,不能反复的元素形成;在计算机中,汇合通常标识的构造中元素是不容许反复的。也能够将汇合看成非凡的数组,非凡之处在于外面的元素没有程序,也不能反复。没有程序意味着不能通过下标值进行拜访,不能反复意味着雷同的对象在汇合中只会存在一份

封装汇合以及汇合间的操作

学习汇合还是和之前一样,咱们这里基于js的对象封装一个汇合类;

汇合的常见操作

add(val):向汇合增加一个新的项。
remove(val):从汇合移除一个值
has(val):如果值在汇合中返回true否则返回false
clear():移除汇合中的所有项
size():返回汇合所蕴含元素的数量。与数组的length属性相似
values();返回一个蕴含汇合中所有值的数组

汇合间的操作

并集:对于给定的两个汇合,返回一个蕴含两个汇合中所有元素的新汇合
交加:对于给定的两个汇合,返回一个蕴含两个汇合中共有元素的新汇合
差集:对于给定的两个汇合,返回一个蕴含所有存在于第一个汇合且不存在于第二个汇合的元素新汇合
子集:验证一个给定汇合是否是另一汇合的子集

 class Set { constructor() { this.items = {}; } add(val) { if (this.has(val)) { return false } this.items[val] = val; return true; } has(val) { return this.items.hasOwnProperty(val) } remove(val) { delete this.items[val] } clear() { this.items = {} } size() { return Object.keys(this.items).length } values() { return Object.keys(this.items) } Union(otherSet) { let obj = new Set(); let currentValues = this.values(); for (let i = 0; i < currentValues.length; i++) { obj.add(currentValues[i]); } let otherValues = otherSet.values(); for (let i = 0; i < otherValues.length; i++) { obj.add(otherValues[i]); } return obj } intersection(otherSet) { let obj = new Set(); let currentValues = this.values(); for (let i = 0; i < currentValues.length; i++) { if (otherSet.has(currentValues[i])) { obj.add(currentValues[i]) } } return obj; } difference(otherSet) { let obj = new Set(); let currentValues = this.values(); for (let i = 0; i < currentValues.length; i++) { if (!otherSet.has(currentValues[i])) { obj.add(currentValues[i]) } } return obj; } subset(otherSet) { let currentValues = this.values(); for (let i = 0; i < currentValues.length; i++) { if (!otherSet.has(currentValues[i])) { return false } } return true; } } let newSet = new Set(); newSet.add('abc'); newSet.add('cba'); newSet.add('nba'); // 汇合的删除办法 newSet.remove('小强') //   汇合的增加和返回一个蕴含汇合中所有值的数组 alert(newSet.values()) //   如果值在汇合中返回true否则返回false alert(newSet.has('小张')) //   汇合中元素的个数 alert(newSet.size()) //   清空集合办法 newSet.clear() alert(newSet.values()) let otherSet = new Set(); otherSet.add('aaa'); otherSet.add('cba'); otherSet.add('nba'); //   并集 let obj = newSet.Union(otherSet) alert(obj.values()) // 交加 let intersectionObj = newSet.intersection(otherSet); alert(intersectionObj.values()) // 差集 let differenceObj = newSet.difference(otherSet); alert(differenceObj.values()) // 子级 alert(newSet.subset(otherSet))