核心提示:集合: 无序不重复/* Set 集合:不重复并且无序*/function Set() { var items = {}; /*集合中添加一个元素*/ this.add = function(value...
集合: 无序不重复
/*
Set
集合:不重复并且无序
*/
function Set() {
var items = {};
/*集合中添加一个元素*/
this.add = function(value) {
if(!this.has(value)) {
items[value] = value;
return true;
}
return false;
}
/*从集合中删除一个元素*/
this.remove = function (value) {
if(this.has(value)) {
delete items[value];
return true;
}
return false;
}
/*判断集合中是否存在某个元素*/
this.has = function (value) {
return items.hasOwnProperty(value);
// return value in items;
}
/*清空集合*/
this.clear = function () {
items = {};
}
/*集合的大小*/
this.size = function () {
var cnt = 0;
for(var name in items) {
if(this.has(name)) {
cnt++
}
}
return cnt;
}
/*返回一个包含集合中所有元素的数组*/
this.values = function () {
var arr = [];
for(var name in items) {
if(this.has(name)) {
arr.push(items[name]);
}
}
return arr;
}
this.print = function () {
console.log(this.values());
}
/*并集*/
this.union = function (other_set) {
var new_set = new Set();
var values = this.values();
for(var i=0; i


