<!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 = {
}
// add方法
Set.prototype.add = function(value) {
if (this.has(value)) {
return false
}
this.items[value] = value;
return true
}
Set.prototype.has = function(value) {
return this.items.hasOwnProperty(value)
}
Set.prototype.remove = function(value) {
//1.判断改元素否含有此元素
if (!this.has(value)) {
return false
}
delete this.items[value]
return true
}
Set.prototype.claer = function() {
this.items = {}
}
Set.prototype.size = function() {
return Object.keys(this.items).length
}
Set.prototype.values = function() {
return Object.keys(this.items)
}
//并集
Set.prototype.union = function(otherSet) {
var unionset = new Set();
var values = this.values()
for (var i = 0; i < values.length; i++) {
unionset.add(values[i])
}
values = otherSet.values()
for (var i = 0; i < values.length; i++) {
unionset.add(values[i])
}
return unionset
}
//交集
Set.prototype.interSection = function(otherSet) {
var intersection = new Set();
var values = this.values()
for (var i = 0; i < values.length; i++) {
var items = values[i]
if (otherSet.has(items)) {
intersection.add(items)
}
}
return intersection
}
//差集
Set.prototype.difference = function(otherSet) {
var differenceset = new Set();
var values = this.values()
for (var i = 0; i < values.length; i++) {
var items = values[i]
if (!otherSet.has(items)) {
differenceset.add(items)
}
}
return differenceset
}
//子集
Set.prototype.sebSet = function(otherSet) {
var values = this.values()
for (var i = 0; i < values.length; i++) {
var items = values[i]
if (!otherSet.has(items)) {
return false;
}
}
return true
}
}
var set1 = new Set()
set1.add('sds')
set1.add('sds')
set1.add('sas')
set1.add('ss')
console.log(set1)
set1.remove('ss')
console.log(set1.size())
var set2 = new Set()
set2.add('sds')
set2.add('s1ds')
set2.add('sa1')
set2.add('ss1')
unionset = set1.union(set2)
console.log(unionset.values())
console.log(set1.interSection(set2).values())
console.log(set1.difference(set2).values())
console.log(set1.sebSet(set2))
</script>
</body>
</html>
集合运算 交集 并集 差集 子集 JS
最新推荐文章于 2022-05-29 13:18:18 发布