js 实现hashtable
实现哈希表的基本结构
哈希表(HashTable)是一种通过键(Key)直接访问值(Value)的数据结构,核心在于哈希函数将键映射到存储位置。以下是用 JavaScript 实现哈希表的关键步骤:
class HashTable {
constructor(size = 32) {
this.size = size;
this.buckets = new Array(size).fill(null).map(() => []);
}
}
哈希函数设计
哈希函数需将任意键转换为固定范围的索引。常用方法是结合字符编码和取模运算:

_hash(key) {
let hash = 0;
for (let i = 0; i < key.length; i++) {
hash = (hash + key.charCodeAt(i) * i) % this.size;
}
return hash;
}
处理键值对插入
使用链地址法解决冲突,将相同哈希值的键值对存储在同一个桶(Bucket)中:

set(key, value) {
const index = this._hash(key);
const bucket = this.buckets[index];
const existingEntry = bucket.find(entry => entry.key === key);
if (existingEntry) {
existingEntry.value = value; // 更新现有键
} else {
bucket.push({ key, value }); // 新增键值对
}
}
获取键对应的值
通过哈希定位桶后,遍历桶内元素查找匹配的键:
get(key) {
const index = this._hash(key);
const bucket = this.buckets[index];
const entry = bucket.find(entry => entry.key === key);
return entry ? entry.value : undefined;
}
删除键值对
从桶中过滤掉指定键的元素:
delete(key) {
const index = this._hash(key);
const bucket = this.buckets[index];
this.buckets[index] = bucket.filter(entry => entry.key !== key);
}
完整代码示例
class HashTable {
constructor(size = 32) {
this.size = size;
this.buckets = new Array(size).fill(null).map(() => []);
}
_hash(key) {
let hash = 0;
for (let i = 0; i < key.length; i++) {
hash = (hash + key.charCodeAt(i) * i) % this.size;
}
return hash;
}
set(key, value) {
const index = this._hash(key);
const bucket = this.buckets[index];
const existingEntry = bucket.find(entry => entry.key === key);
if (existingEntry) {
existingEntry.value = value;
} else {
bucket.push({ key, value });
}
}
get(key) {
const index = this._hash(key);
const bucket = this.buckets[index];
const entry = bucket.find(entry => entry.key === key);
return entry ? entry.value : undefined;
}
delete(key) {
const index = this._hash(key);
const bucket = this.buckets[index];
this.buckets[index] = bucket.filter(entry => entry.key !== key);
}
}
性能优化建议
- 动态扩容:当元素数量超过阈值(如负载因子 > 0.75),倍增桶的数量并重新哈希所有键值对。
- 更好的哈希函数:可使用加密哈希函数(如SHA-1)的简化版减少冲突。
- 开放寻址法:作为链地址法的替代方案,直接在数组中寻找空闲位置存储冲突元素。






