ES6也實現了Set類型。
我們看到
var set = new Set([1, 2, 2, 3, 3]);
console.log(set);
看下面的註釋部分。由於使用的是函數表達式(對應的是函數聲明)。因此代碼得放在合理的位置
/*
使用數組來模擬集合
*/
function Set(arr) {
var items = [];
this.add = function (value) {
if(this.has(value)) {
return false;
}
items.push(value);
return true;
}
this.has = function (value) {
if(items.indexOf(value) == -1) {
return false;
}
return true;
}
/*添加一些Set初始化的代碼*/
if(arr) {
for(var i=0; i<arr.length; ++i) {
this.add(arr[i])
}
}
this.remove = function (value) {
if(this.has(value)) {
var index = items.indexOf(value);
items.splice(index, 1);
return true;
}
return false;
}
this.clear = function () {
items = [];
}
this.size = function () {
return items.length;
}
this.values = function () {
return items;
}
this.print = function () {
console.log(items);
}
this.union = function (other_set) {
var new_set = new Set();
var values = this.values();
for(var i=0; i<values.length; ++i) {
new_set.add(values[i]);
}
values = other_set.values();
for(var i=0; i<values.length; ++i) {
if(!new_set.has(values[i])) {
new_set.add(values[i]);
}
}
return new_set;
}
this.intersection = function (other_set) {
var new_set = new Set();
var values = this.values();
for(var i=0; i<values.length; ++i) {
if(other_set.has(values[i])) {
new_set.add(values[i]);
}
}
return new_set;
}
this.difference = function (other_set) {
var new_set = new Set();
var values = this.values();
for(var i=0; i<values.length; ++i) {
if(!other_set.has(values[i])) {
new_set.add(values[i]);
}
}
return new_set;
}
this.isSubset = function (other_set) {
var flag = true;
var values = other_set.values();
for(var i=0; i<values.length; ++i) {
if(!this.has(values[i])) {
return false;
}
}
return true;
}
}
var set = new Set([1, 2, 2, 1, 3]);
set.print();