1 <!DOCTYPE html>
2 <html>
3 <head>
4 <meta charset="UTF-8">
5 <title>散列</title>
6 </head>
7 <body>
8 <script>
9 function HashTable(){
10 this.table = new Array(137);
11 this.betterHash = betterHash;
12 this.showDistro = showDistro;
13 this.put = put;
14 this.get = get;
15 }
16 function betterHash(data){
17 const H =37;
18 var total = 0;
19 for(var i=0;i<data.length;i++){
20 total += H*total + data.charCodeAt(i);
21
22 }
23 total %= this.table.length;
24 if(total <0){
25 total += this.table.length-1;
26 }
27 console.log(total,"total")
28 return parseInt(total);
29 }
30
31 function put(key,data){
32 var pos = this.betterHash(key);
33 this.table[pos] = data;
34 }
35 function showDistro(){
36 var n = 0;
37 for(var i = 0;i<this.table.length;i++){
38 if(this.table[i] != undefined){
39 console.log(i,":",this.table[i]);
40 }
41 }
42 }
43 function get(key){
44 return this.table[this.betterHash(key)];
45 }
46
47
48
49 var obj = new HashTable();
50 obj.put("k1","zhangsan");
51 obj.put("k2","lisi");
52 obj.put("k3","javascript");
53 obj.showDistro();
54 console.log(obj.get("k3"));
55 </script>
56 </body>
57 </html>