集合

几乎每种变成语言中,都有集合结构。集合通常是由一组无序的,不能重复的元素构成;在计算机中,集合通常标识的结构中元素是不允许重复的。也可以将集合看成特殊的数组,特殊之处在于里面的元素没有顺序,也不能重复。没有顺序意味着不能通过下标值进行访问,不能重复意味着相同的对象在集合中只会存在一份

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

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

集合的常见操作

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

集合间的操作

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

image.png

image.png

image.png

image.png

 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))

mengyuhang4879
13 声望7 粉丝