集合(set)是一组无序的,但彼此之间又有一定相关性的数据集。每个成员在数组中只能出现一次。
在使用集合(set)之前最好先理解一下内容:
1、不包含任何成员的集合称为空集合。
2、如果两个集合的成员都相等,两个集合相等。
3、如果一个集合中的成员都在另一个集合中,则两个具有父子集的关系。
在集合中我们常用的操作就是:求集合的并集,交集,补集等。
下面我们基于数组该构建一个集合(Set)类。
<html>
<head>
<title>Date Example</title>
</head>
<body>
<div id="content"></div>
<input type="button" value="Set InnerHTML" onclick="testDate()">
<script type="text/javascript">
function Set() {
this.dataStore = [];
// 添加元素
this.add = function (data){
if (this.dataStore.indexOf(data) < 0) {
this.dataStore.push(data);
return true;
}
else {
return false;
}
};
// 删除元素
this.remove = function (){
var pos = this.dataStore.indexOf(data);
if (pos > -1) {
this.dataStore.splice(pos,1);
return true;
}
else {
return false;
}
};
this.size = function (){
return this.dataStore.length;
};
// 求两个集合的并集
this.union = function (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;
};
// 查询集合中是否包含某个元素
this.contains = function (data{
if (this.dataStore.indexOf(data) > -1) {
return true;
}
else {
return false;
}
};
// 两个集合的交集
this.intersect = function (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;
};
// 查询set是不是现在集合的子集
this.subset = function (set){
if (this.size() > set.size()) {
return false;
}
else {
for each (var member in this.dataStore) {
if (!set.contains(member)) {
return false;
}
}
}
return true;
};
// 两个集合的补集
this.difference = function (){
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;
};
this.show = function (){
return "[" + this.dataStore + "]";
};
}
</script>
</body>
</html>
javascript Set data structures
原文:http://www.cnblogs.com/duhuo/p/5081318.html