数据结构5-集合

概述

编程语言中的集合,主要有几个特点

  1. 集合中的元素不能重复
  2. 集合是无序的

封装集合类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
function Set(){
this.items = {}
Set.prototype.has = function(element){
return this.items.hasOwnProperty(element);
}
Set.prototype.add = function(element){
if(this.has(element))return false;
this.items[element] = element;
return true;
}
Set.prototype.remove = function(elem){
if(!this.has(elem))return false;
delete this.items[elem];
return true;
}
Set.prototype.clear = function(){
this.items = {};
}
Set.prototype.size = function(){
return Object.keys(this.items).length;
}
Set.prototype.value = function(){
return Object.keys(this.items);
}
}
var s = new Set();
s.add(1);
s.add(2);
s.add(3);
s.add(1);
alert(s.value());