一、集合的概念
集合:集合是一种数学中的概念,集合通常由一组无序的,不能重复的元素构成,可以看作是特殊的数组,(注意没有顺序意味着不能通过下标值进行访问,不能重复意味着相同的对象在集合中只会存在一份.)也就是es6里面的set
二、封装常见的集合操作
add(value)∶向集合添加一个新的项。
remove(value):从集合移除一个值。
has(value):如果值在集合中,返回true,否则返回false。
clear():移除集合中的所有项。
size():返回集合所包含元素的数量。与数组的length属性类似。
values():返回一个包含集合中所有值的数组。
function Set() {
this.items = {}
//增加
this.add = function (value) {
if (!this.items[value]) { //方括号语法来访问item对象里面的值,.语法存在缺点,不可以后面跟着变量,只能是对象名
this.items[value] = value
return value
}
return false
}
// 查找
this.has = function (value) {
return this.items.hasOwnProperty(value)
}
// 移除
this.remove = function (value) {
if (this.items[value]) {
delete this.items[value]
return true
}
return false
}
//获取
this.getItems = function () {
return this.items
}
//长度
this.size = function () {
return Object.keys(this.items).length
}
//值
this.values = function () {
return Object.keys(this.items)
}
//清空
this.clear = function () {
this.items = {}
}
}
var set = new Set()
set.add(1)
set.add(2)
set.add(3)
set.has(3)
set.remove(3)
二、集合间操作
Set.prototype.union = function (otherSet) {
var unionSet = new Set()
var arrs = this.values()
for (var i = 0; i < arrs.length; i++) {
unionSet.add(arrs[i])
}
var arr = otherSet.values()
for (var i = 0; i < arr.length; i++) {
unionSet.add(arr[i])
}
return unionSet.values()
}
// 交集
Set.prototype.intersection = function (otherSet) {
var intersectionSet = new Set()
var value = this.values()
for (var i = 0; i < value.length; i++) {
var item = value[i]
if (otherSet.has(item)) {
intersectionSet.add(item)
}
}
return intersectionSet.values()
}
//差集
Set.prototype.difference = function (otherSet) {
var differenceSet = new Set()
var value = this.values()
for (var i = 0; i < value.length; i++) {
var item = value[i]
if (!otherSet.has(item)) {
differenceSet.add(item)
}
}
return differenceSet.values()
}
Set.prototype.subset = function (otherSet) {
var value = this.values()
for (var i = 0; i < value.length; i++) {
if (!otherSet.has(value[i])) {
return false
}
}
return true
}
}
var set = new Set()
set.add(1)
set.add(2)
set.add(3)
set.add(5)
var setA = new Set()
setA.add(5)
setA.add(6)
setA.add(3)
var setB = new Set()
setB.add(1)
setB.add(2)
三、es6里面的set
1.set可以使用forEach方法,如果传入的是value1,value2两个参数会返回键和值相同的数 ,如果传入index,item则会返回下标和下标对应的值
2.set具有interator的属性,通过var interator=set.entries()可以构造迭代器,具有next方法