-
集合
指具有某种特定性质的具体的或抽象的对象汇总成的集体
-
空集
不包含任何元素
- 子集
- 并集
- 交集
- 补集
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>集合</title>
</head>
<body>
<script>
function Set() {
this.dataStore = [];
this.add = add;
this.remove = remove;
this.show = show;
this.union = union;
this.intersect = intersect;
this.difference = difference;
this.contains = contains;
this.size = size;
this.subset = subset;
}
function add(data) {
if (this.dataStore.indexOf(data) < 0) {
this.dataStore.push(data);
} else {
return false
}
}
function remove(data) {
var pos = this.dataStore.indexOf(data);
if (pos > -1) {
this.dataStore.splice(pos, 1)
} else {
return false
}
}
function show() {
return this.dataStore;
}
function contains(data) {
if (this.dataStore.indexOf(data) > -1) {
return true;
} else {
return false;
}
}
function union(set) {
// 并集
var temSet = new Set();
for (var i = 0; i < this.size(); i++) {
temSet.add(this.dataStore[i]);
}
for (i = 0; i < set.size(); i++) {
if (!temSet.contains(set.dataStore[i])) {
temSet.dataStore.push(set.dataStore[i]);
}
}
return temSet;
}
function intersect(set) {
// 补集
var temSet = new Set();
for (var i = 0; i < this.size(); i++) {
if (set.contains(this.dataStore[i])) {
temSet.add(this.dataStore[i])
}
}
return temSet;
}
function difference(set) {
// 补集
var temSet = new Set();
for (var i = 0; i < this.size(); i++) {
if (!set.contains(this.dataStore[i])) {
temSet.add(this.dataStore[i])
}
}
return temSet;
}
function size() {
return this.dataStore.length;
}
function subset(set) {
// set是否是当前的子集
if (set.size() > this.size()) {
return false
} else {
for (var i = 0; i < set.size(); i++) {
if (!this.contains(set.dataStore[i])) {
return false;
}
}
return true;
}
}
var names = new Set();
names.add('晓红');
names.add('小明');
names.add('小李');
names.add('小张');
console.log(names.show());
names.remove('小张');
console.log(names.show());
var cis = new Set();
cis.add('晓红');
// cis.add('ahs');
// cis.add('abi');
// cis.add('ahe');
console.log('cis:', cis.show());
names.subset(cis); // true
console.log('并集', cis.union(names));
console.log('交集', cis.intersect(names));
console.log('补集', cis.difference(names));
</script>
</body>
</html>
网友评论