绪论
集合的特点: 元素无序,不允许重复。
集合的方法:
- values:获取集合中的所有元素。
- size:获取集合中元素个数。
- has:判断集合中是否存在某个元素。
- add:添加元素。
- remove:移除某个元素。
- union:获取两个集合的并集。
- intersection:获取两个集合的交集。
- difference:获取两个集合的差集。
- subset:判断一个集合是否为另一个集合的子集。
正文
<!DOCTYPE html>
<div 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>index</title>
<script src="js/jquery-2.2.4.min.js"></script>
<style>
</style>
</head>
<body>
</body>
<script>
$(document).ready(function () {
var set_1 = new mySet();
set_1.add(1);
set_1.add(2);
set_1.add(3);
set_1.add(2);
set_1.add(5);
var set_2 = new mySet();
set_2.add(2);
set_2.add(4);
var set_3 = new mySet();
set_3.add(1);
set_3.add(3);
console.log('set_1元素:' + set_1.values());
console.log('set_1长度:' + set_1.size());
console.log('set_2元素:' + set_2.values());
console.log('set_2长度:' + set_2.size());
console.log('set_3元素:' + set_3.values());
console.log('set_3长度:' + set_3.size());
console.log('set_1是否存在3:' + set_1.has(3));
console.log('set_1是否存在4:' + set_1.has(4));
console.log('set_1移除5:' + set_1.remove(5));
console.log('set_1元素:' + set_1.values());
console.log('set_1长度:' + set_1.size());
console.log('set_1和set_2并集:' + set_1.union(set_2).values());
console.log('set_1和set_2交集:' + set_1.intersection(set_2).values());
console.log('set_1和set_2差集:' + set_1.difference(set_2).values());
console.log('set_2是否为set_1的子集:' + set_2.subset(set_1));
console.log('set_3是否为set_1的子集:' + set_3.subset(set_1));
});
function mySet() {
var arr = [];
// 获取集合中的所有元素
this.values = function() {
return arr;
};
// 获取集合中元素个数
this.size = function() {
return arr.length;
};
// 判断集合中是否存在某个元素
this.has = function(v) {
return arr.indexOf(v) !== -1;
};
// 添加元素
this.add = function(v) {
if (!this.has(v)) {
arr.push(v);
return true;
}
return false;
};
// 移除某个元素
this.remove = function(v) {
if (this.has(v)) {
var index = arr.indexOf(v);
arr.splice(index, 1);
return true;
}
return false;
};
// 获取两个集合的并集
this.union = function(otherSet) {
var unionSet = new mySet();
this.values().forEach(function(v) {
unionSet.add(v);
});
otherSet.values().forEach(function(v) {
unionSet.add(v);
});
return unionSet;
};
// 获取两个集合的交集
this.intersection = function(otherSet) {
var intersectionSet = new mySet();
this.values().forEach(function(v) {
if (otherSet.has(v)) {
intersectionSet.add(v);
}
});
return intersectionSet;
};
// 获取两个集合的差集
this.difference = function(otherSet) {
var differenceSet = new mySet();
this.values().forEach(function(v) {
if (!otherSet.has(v)) {
differenceSet.add(v);
}
});
return differenceSet;
};
// 判断一个集合是否为另一个集合的子集
this.subset = function(otherSet) {
return this.values().every(function(v) {
return otherSet.has(v);
});
};
}
</script>
</div>
结果
(若有什么错误,请留言指正,3Q)