*JS实现HashTable的例子
1
<script language="javascript" type="text/javascript">
2
3
function Hashtable()
4
{
5
this._hash = new Object();
6
this.add = function(key,value){
7
if(typeof(key)!="undefined"){
8
if(this.contains(key)==false){
9
this._hash[key]=typeof(value)=="undefined"?null:value;
10
return true;
11
} else {
12
return false;
13
}
14
} else {
15
return false;
16
}
17
}
18
this.remove = function(key){delete this._hash[key];}
19
this.count = function(){var i=0;for(var k in this._hash){i++;} return i;}
20
this.items = function(key){return this._hash[key];}
21
this.contains = function(key){ return typeof(this._hash[key])!="undefined";}
22
this.clear = function(){for(var k in this._hash){delete this._hash[k];}}
23
24
}
25
26
var a = new Hashtable();
27
28
a.add("aa");
29
a.add("bb",2342);
30
a.add("bb",2342);
31
32
a.remove("aa");
33
34
alert(a.count());
35
36
alert(a.contains("bb"));
37
38
alert(a.contains("aa"));
39
40
alert(a.items("bb"));
41
42
43
</script>
<script language="javascript" type="text/javascript">2

3
function Hashtable()4
{5
this._hash = new Object();6
this.add = function(key,value){7
if(typeof(key)!="undefined"){8
if(this.contains(key)==false){9
this._hash[key]=typeof(value)=="undefined"?null:value;10
return true;11
} else {12
return false;13
}14
} else {15
return false;16
}17
}18
this.remove = function(key){delete this._hash[key];}19
this.count = function(){var i=0;for(var k in this._hash){i++;} return i;}20
this.items = function(key){return this._hash[key];}21
this.contains = function(key){ return typeof(this._hash[key])!="undefined";}22
this.clear = function(){for(var k in this._hash){delete this._hash[k];}}23

24
}25

26
var a = new Hashtable();27

28
a.add("aa");29
a.add("bb",2342);30
a.add("bb",2342);31

32
a.remove("aa");33

34
alert(a.count());35

36
alert(a.contains("bb"));37

38
alert(a.contains("aa"));39

40
alert(a.items("bb"));41

42

43
</script>



浙公网安备 33010602011771号