1 集合结构的特点
- 集合比较常见的实现方式是哈希表
- 集合通常是一组无序的,不能重复的元素构成
- 和数学中的集合名词比较相似,但是数学中的集合范围更大一些,也许集合中的元素重复
- 在计算机中,集合通常表示的结构中的元素是不允许重复的
- 集合是特殊的数组
- 特殊之处在于里面的元素没有顺序,也不能重复
- 没有顺序意味着不能通过下标值进行访问,不能重复意味着相同的对象在集合中只会存在一份
2 集合中常见的方法
- add(value):向集合添加一个新的项。
- remove(value):从集合移除一个值。
- has(value):如果值在集合中,返回true,否则返回false。
- clear():移除集合中的所有项。
- size():返回集合所包含元素的数量。与数组的length属性类似。
- values():返回一个包含集合中所有值的数组。
- …
3 集合间的操作
- 并集
- 交集
- 差集
- 子集
4 封装集合类
function Set() {
//属性
this.items = {}
//方法
//add 方法
Set.prototype.add = function(value){
//判断当前集合中是否已经包含了该元素
if(this.has(value)){
return false;
}
//将元素添加到集合中
this.items[value] = value;
return true;
}
//has方法
Set.prototype.has = function(value){
return this.items.hasOwnProperty(value);
}
//remove方法
Set.prototype.remove = function(value){
//1.判断集合中是否包含该元素
if(!this.has(value)){
return false
}
//2.将元素从属性中删除
delete this.items[value];
return true;
}
//clear方法
Set.prototype.clear = function() {
this.items = {};
}
//size方法
Set.prototype.size = function() {
return Object.keys(this.items).length;
}
//获取集合中所有的值 values方法
Set.prototype.values = function() {
return Object.keys(this.items);
}
//集合间的操作
//并集
Set.prototype.union = function(otherSet) {
//this:集合对象A
//otherSet:集合对象B
//1.创建新的集合
var unionSet = new Set();
//2.将集合A中的所有元素添加到新集合中
var values1 = this.values();
for(var i = 0;i < values1.length;i++){
unionSet.add(values1[i])
}
//3.取出B集合中的元素,判断是否需要添加到新集合
var values2 = otherSet.values();
for(var i = 0;i < values2.length;i++){
unionSet.add(values2[i])
}
return unionSet;
}
//交集
Set.prototype.intersection = function(otherSet){
//this: 集合A
//otherSet: 集合B
//1.创建新集合
var intersectionSet = new Set();
//2.从A中取出一个个元素,判断是否同时存在与集合B中,存入新集合
var values = this.values();
for(var i = 0;i < values.length; i++){
var item = values[i];
if(otherSet.has(item)){
intersectionSet.add(item)
}
}
return intersectionSet;
}
//差集
Set.prototype.defference = function(otherSet){
//this: 集合A
//otherSet: 集合B
//1.创建新集合
var intersectionSet = new Set();
//2.从A中取出一个个元素,判断是否同时存在与集合B中,存入新集合
var values = this.values();
for(var i = 0;i < values.length; i++){
var item = values[i];
if(!otherSet.has(item)){
intersectionSet.add(item)
}
}
return intersectionSet;
}
//判断当前集合是否是其它集合的子集
Set.prototype.subSet = function (otherSet){
//this: 集合A
//otherSet: 集合B
//遍历集合A中所有元素,如果发现,集合A中的元素在集合B中不存在,那么返回false
//如果遍历完了整个集合依然没有返回false,返回true即可
var values = this.values();
for(var i = 0;i < values.length; i++){
var item = values[i];
if(!otherSet.has(item)){
return false;
}
}
return true;
}
}