集合是由一组无序且唯一(即不能重复)的项组成的。可以将集合想象成一个既没有重复元素,也没有顺序概念的数组。
基于ES2015的Set类来实现我自己的Set类。需要声明以下集合可用的方法:
- add(element): 向集合添加一个新元素。
- delete(element): 从集合移除一个元素。
- has(element): 如果元素在集合中,返回true,否则返回false。
- clear(): 移除集合中的所有元素。
- size(): 返回集合所包含元素的数量。它与数组的length属性相同。
- values(): 返回一个包含集合中所有值(元素)的数组。
class Set {
constructor() {
// 对象不允许一个键值指向两个不同的属性,保证了集合里元素的唯一性
this.items = {};
}
has(element) {
// 两种方法
// return element in this.items;
return Object.prototype.hasOwnProperty.call(this.items, element);
}
add(element) {
if(!this.has(element)) {
this.items[element] = element;
return true;
}
return false;
}
delete(element) {
if(this.has(element)) {
delete this.items[element];
return true;
}
return false;
}
clear() {
this.items = {};
}
size() {
// 两种方法
// return Object.keys(this.items).length;
let count = 0;
for(let key in this.items) {
if(this.items.hasOwnProperty(key)) {
count++;
}
}
return count;
}
values() {
return Object.values(this.items);
}
}
ECMAScript2015——Set类
可以使用Set类和扩展运算符实现并集、交集、差集的简便方法。
并集:
交集:
差集:
在数学中,有一个叫作多重集(或袋)的概念,它允许我们向集合中插入之前已经添加过的元素。