并集:将两个集合中的成员进行合并,得到一个新的集合
交集:两个集合共同存在的成员组成一个新的集合
补集:属于一个集合而不属于另一个集合的成员组成的集合
function Set() {
this.dataStore = [];
this.add = add;
this.remove = remove;
this.show = show;
this.contains = contains;
this.size = size;
this.union = union;
this.intersect = intersect;
this.subset = subset;
this.difference = difference;
}
//添加元素(不含相同元素)
function add(data) {
if (this.dataStore.indexOf(data) < 0) {
this.dataStore.push(data);
return true;
} else {
return false;
}
}
//移除元素
function remove(data) {
var pos = this.dataStore.indexOf(data);
if (pos > -1) {
this.dataStore.splice(pos,1);
return true;
} 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 tempSet = new Set();
for (var i=0; i<this.dataStore.length; i++) {
tempSet.add(this.dataStore[i]);
}
for (var i=0; i<set.dataStore.length; i++) {
if (!tempSet.contains(set.dataStore[i])) {
tempSet.dataStore.push(set.dataStore[i]);
}
}
return tempSet;
}
//交集-当第一个集合也属于第二个集合时,该成员加入一个新集合
function intersect(set) {
var tempSet = new Set();
for (var i=0; i<this.dataStore.length; i++) {
if (set.contains(this.dataStore[i])) {
tempSet.add(this.dataStore[i]);
}
}
return tempSet;
}
//补集-判断该集合长度是否小于待比较集合,再判断集合内的成员是否都属于待比较成员
function subset(set) {
if (this.size() > set.size()) {
return false;
} else {
for(var member in this.dataStore) {
if (!set.contains(this.dataStore[member])) {
return false;
}
}
return true;
}
}
//集合长度
function size() {
return this.dataStore.length;
}
//差集-返回属于第一个集合但不属于第二个集合的成员
function difference(set) {
var tempSet = new Set();
for (var i=0; i<this.dataStore.length; i++) {
if (!set.contains(this.dataStore[i])) {
tempSet.add(this.dataStore[i]);
}
}
return tempSet;
}
var s = new Set();
s.add('b');
s.add('9');
var h = new Set();
h.add('b');
h.add('g');
var all = s.difference(h);
console.log(all.show())
es6 基于Set 实现并集(Union)、交集(Intersect)和差集(Difference)。
let a = new Set([1, 2, 3]);
let b = new Set([4, 3, 2]);
// 并集
let union = new Set([...a, ...b]);
// Set {1, 2, 3, 4}
// 交集
let intersect = new Set([...a].filter(x => b.has(x)));
// set {2, 3}
// 差集
let difference = new Set([...a].filter(x => !b.has(x)));
// Set {1}
使用ES6 Set实现JavaScript集合操作:并集、交集、差集

这篇博客介绍了如何使用ES6中的Set数据结构来实现JavaScript集合的常见操作,包括合并两个集合得到并集,找出两个集合的交集,以及计算集合的补集。通过实例展示了如何进行这些操作。
635

被折叠的 条评论
为什么被折叠?



