集合:集合通常是由一组无序的,不能重复的元素构成,不能通过下标值访问。
集合的操作:
- 并集:对于给定的两个集合,返回一个包含两个集合中所有元素的新集合。
- 交集:对于给定的两个集合,返回一个包含两个集合中共有元素的新集合。
- 差集:对于给定的两个集合,返回一个包含所有存在于第一个集中且不存在于第二个元素的新集合。
- 子集:一个集合被另一个集合所包含。
代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
//封装集合类
function Set(){
//属性
this.items = {}
//方法
//1.add方法
Set.prototype.add = function (value){
//判断集合中是否包含该元素
if(this.has(value)) return false
//将元素添加到集合中
this.items[value] = value
return true
}
//2.has方法
Set.prototype.has = function (value){
return this.items.hasOwnProperty(value)
}
//3.remove方法
Set.prototype.remove = function (value){
// 判断集合中是否有该元素
if(this.has(value)) return false
//删除该元素
delete this.items[value]
return true
}
// 4.clear方法
Set.prototype.clear = function (value){
this.items = {}
}
//5.size方法
Set.prototype.size = function (value){
return Object.keys(this.items).length
}
//6.获取集合中所有的值
Set.prototype.values = function (){
return Object.keys(this.items)
}
//集合间的操作
// 1.并集
Set.prototype.union = function (others){
// 将this看作集合a,others看作集合B
//创建新集合
var newSet = new Set();
//将A中元素添加到新集合中
var values = this.values()
for(let i = 0; i < values.length; i++){
newSet.add(values[i])
}
//将B中元素添加到新集合中
values = others.values()
for(let i = 0; i < values.length; i++){
newSet.add(values[i])
}
return newSet
}
// 2.交集
Set.prototype.intersection = function (others){
//创建新集合
var newSet = new Set();
//遍历this,取出this中的所有元素,并看others中是否也存在该元素,将this与others都存在的元素放入新集合内
var values = this.values()
for(let i = 0; i < values.length; i++){
if(others.has(values[i])) newSet.add(values[i])
}
return newSet
}
//3.差集
Set.prototype.difference = function (others){
//创建新集合
var newSet = new Set();
//遍历this,取出this中的所有元素,若others中不存在该元素,将该元素放入新集合内
var values = this.values()
for(let i = 0; i < values.length; i++){
if(!others.has(values[i])) newSet.add(values[i])
}
return newSet
}
//子集
Set.prototype.subset = function (others){
//判断others是不是this的子集
// var values = this.values()
// for(let i = 0; i < values.length; i++){
// if(!others.has(values[i])) return false
// }
// return true
return others.values().every(i => this.values().includes(i))
}
}
var a = new Set();
var b = new Set();
a.add("aaa")
a.add("bbb")
a.add("ccc")
b.add("aaa")
b.add("bbb")
b.add("ddd")
alert(a.union(b).values())
alert(a.intersection(b).values())
alert(a.difference(b).values())
alert(a.subset(b))
</script>
</body>
</html>