设计一个构造函数IntSet,包括属性 len(集合的长度)和集合web_set(存放元素),以及如下方法:
insert(val) 向集合中添加一个元素,重复的元素不能添加
length() 返回集合的元素个数
getInt(index) 返回集合中位置index的元素
disp() 输出集合的所有元素
union(s2) 实现两个集合的并运算
intersection(s2) 实现两个集合的交运算
difference(s2) 实现两个集合的差运算
要求:定义两个整数集合{2,4,1,3,5}和{2,5,10},输出前者的元素个数以及它们进行集合的并、交、差运算
<body>
<script>
function IntSet(){
this.web_set = new Set();
this.len = this.web_set.size
//length() 返回集合的元素个数
this.length = function(){
return this.len
}
// insert(val) 向集合中添加一个元素,重复的元素不能添加
this.insert = function(...args){
for(let t of args){ //arguments是函数的内置对象:是一个数组,用户传递的实参个数
this.web_set.add(t)
}
this.len = this.web_set.size
}
//getInt(index) 返回集合中位置index的元素
this.getInt = function(index){
let arr = [...this.web_set]
if(index >=0 && index < arr.length){
return arr[index];
}else{
return undefined;
}
}
//disp() 输出集合的所有元素
this.disp = function(){
console.log('集合元素是:')
console.log(this.web_set) //{2, 5, 10}
}
//union(s2) 实现两个集合的并运算
this.union = function(s2){
let bj =new Set([...this.web_set,...s2.web_set])
return bj
}
//intersection(s2) 实现两个集合的交运算
this.intersection = function(s2){
let arr = [...this.web_set]
let temp = arr.filter(function(item){
if(s2.web_set.has(item)){
return item
}
})
return temp
}
//difference(s2) 实现两个集合的差运算
this.difference = function(s2){
let arr = [...this.web_set]
let temp =arr.filter(function(item){
return !s2.web_set.has(item)
})
return temp
}
}
let set1 = new IntSet();
set1.insert(2,4,1,3,5)
set1.disp()
console.log('Set1的长度:',set1.length()) //5
let set2 = new IntSet()
set2.insert(2,5,10)
set2.disp()
let bj = set1.union(set2)
//{2,4,1,3,5,10}
console.log('Set1和Set2的并集:',bj)
//[2, 5]
console.log('Set1和Set2的交集:',set1.intersection(set2))
//[4, 1, 3]
console.log('Set1和Set2的差集:',set1.difference(set2))
</script>
</body>