File tree Expand file tree Collapse file tree 1 file changed +61
-0
lines changed
Expand file tree Collapse file tree 1 file changed +61
-0
lines changed Original file line number Diff line number Diff line change 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 >
You can’t perform that action at this time.
0 commit comments