您的位置:首页 > 其它

集合的实现3--ES6的set类型

2017-10-05 14:55 435 查看
ES6也实现了Set类型。

ES6入门之set和map

我们看到

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();
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: