# JS中数据结构之散列表

HashTable类

```function HashTable() {
this.table = new Array(137);
this.simpleHash = simpleHash;
this.showDistro = showDistro;
this.put = put;
this.get = get;
this.buildChains = buildChains;
}```

```function simpleHash(data) {
var total = 0;
for (var i = 0; i < data.length; ++i) {
total += data.charCodeAt(i);
}
}```

put() 和 showDistro()，一个用来将数据存入散列表， 一个用来显示散列表中的数据

```function put(data) {
var pos = this.simpleHash(data);
this.table[pos] = data;
}
function showDistro() {
var n = 0;
for (var i = 0; i < this.table.length; ++i) {
if (this.table[i] != undefined) {
print(i + ": " + this.table[i]);
}
}
}```

```function betterHash(string, arr) {
const H = 37;  //质数
var total = 0;
for (var i = 0; i < string.length; ++i) {
total += H * total + string.charCodeAt(i);
}
total = total % arr.length;
return parseInt(total);
}```

```function put(key, data) {
var pos = this.betterHash(key);  //使用更好的散列函数
this.table[pos] = data;
}```

get() 方法读取存储在散列表中的数据

```function get(key) {
return this.table[this.betterHash(key)];
}```

buildChains() 函数创建二维数组

```function buildChains() {
for (var i = 0; i < this.table.length; ++i) {
this.table[i] = new Array();
}
}```

```function put(key, data) {
var pos = this.betterHash(key);
var index = 0;
if (this.table[pos][index] == undefined) {
this.table[pos][index] = key;
this.table[pos][index + 1] = data;
} else {
while (this.table[pos][index] != undefined) {
++index;
}
this.table[pos][index] = key;
this.table[pos][index + 1] = data;
}
}```

```function get(key) {
var index = 0;
var pos = this.betterHash(key);
if (this.table[pos][index] == key) {
return this.table[pos][index + 1];
} else {
while (this.table[pos][index] != key) {
index += 2;
}
return this.table[pos][index + 1];
}
return undefined;
}```

```function put(key, data) {
var pos = this.betterHash(key);
if (this.table[pos] == undefined) {
this.table[pos] = key;
this.values[pos] = data;
} else {
while (this.table[pos] != undefined) {
pos++;
}
this.table[pos] = key;
this.values[pos] = data;
}
}

function get(key) {
var hash = this.betterHash(key);
for (var i = hash; this.table[hash] != undefined; i++) {
if (this.table[hash] == key) {
return this.values[hash];
}
}
return undefined;
}```

原文作者：wenxuehai
原文地址: https://www.cnblogs.com/wenxuehai/p/10288785.html
本文转自网络文章，转载此文章仅为分享知识，如有侵权，请联系博主进行删除。