Skip to content

Commit e9a0aa3

Browse files
Merge pull request #164 from q23wwwwe/master
[js]增加散列表js实现
2 parents e0acfb2 + 31bab47 commit e9a0aa3

File tree

1 file changed

+61
-0
lines changed

1 file changed

+61
-0
lines changed
Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
<!DOCTYPE html>
2+
<html lang="en">
3+
<head>
4+
<meta charset="UTF-8">
5+
<title>Title</title>
6+
</head>
7+
<body>
8+
<script>
9+
/*
10+
最基本的散列表
11+
*/
12+
13+
class HashTable {
14+
constructor() {
15+
this.table=[];
16+
}
17+
//散列函数
18+
loseHashCode(key){
19+
var hash=0;
20+
//从ASCII表中查到的ASCII值加到hash中
21+
for (var i=0;i<key.length;i++){
22+
hash+=key.charCodeAt(i);
23+
}
24+
//为了得到比较小的数值,我们会用hash和任意数除余
25+
return hash%37;
26+
}
27+
//向散列表增加一个新的项
28+
put(key,value){
29+
var position=this.loseHashCode(key);
30+
console.log(position+'-'+key);
31+
this.table[position]=value;
32+
}
33+
//根据键从散列表删除值
34+
remove(key){
35+
this.table[this.loseHashCode(key)]=undefined;
36+
}
37+
//返回根据键值检索到的特定的值
38+
get(key){
39+
console.log(this.table[this.loseHashCode(key)])
40+
}
41+
print(){
42+
for (var i=0;i<this.table.length;++i){
43+
if (this.table[i]!==undefined){
44+
console.log(i+':'+this.table[i]);
45+
}
46+
}
47+
}
48+
}
49+
var hash = new HashTable();
50+
hash.put('Gandalf', '[email protected]');
51+
hash.put('John', '[email protected]');
52+
hash.put('Tyrion', '[email protected]');
53+
hash.remove('Gandalf')
54+
hash.get('Gandalf')
55+
hash.get('Tyrion')
56+
hash.print()
57+
58+
//
59+
</script>
60+
</body>
61+
</html>

0 commit comments

Comments
 (0)