-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHashTab.js
More file actions
49 lines (44 loc) · 1.34 KB
/
HashTab.js
File metadata and controls
49 lines (44 loc) · 1.34 KB
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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
$(function () {
//测试HashTable
let hashTab = new HashTable();
//添加元素
//获取元素
console.log(hashTab.get("andyWqh"));
console.log(hashTab.get("andyWzc"));
console.log(hashTab.get("andy"));
//移除指定键
hashTab.remove("john");
console.log(hashTab.get("john"));
});
//创建散列表数据结构
function HashTable() {
//散列表内部存储数据 以数组为例
let tab = [];
//定义散列表私有方法
let loseloseHashCode = function (key) {
let hash = 0;
for (let i = 0; i < key.length; i++) {
hash = hash + key.charCodeAt(i);
}
return hash % 37;
};
//定义散列表公开方法
//向散列表新增或者更新键值
this.put = function (key, value) {
var position = loseloseHashCode(key);
console.log(position + ' -' + key);
tab[position] = value;
};
//根据键值从散列表中删除值
this.remove = function (key) {
tab[loseloseHashCode(key)] = undefined;
};
//返回根据键值检索的特定值
this.get = function (key) {
return tab[loseloseHashCode(key)];
};
}