js实现hash
JavaScript 实现哈希表的方法
哈希表(Hash Table)是一种通过哈希函数将键映射到存储位置的数据结构。在 JavaScript 中,可以通过对象或 Map 类实现哈希表的功能。
使用对象实现哈希表
JavaScript 的对象本质上是键值对的集合,可以用于实现简单的哈希表。

const hashTable = {};
// 添加键值对
hashTable['key1'] = 'value1';
hashTable['key2'] = 'value2';
// 获取值
console.log(hashTable['key1']); // 输出: value1
// 删除键值对
delete hashTable['key2'];
使用 Map 类实现哈希表
Map 是 ES6 引入的专门用于键值对存储的数据结构,比普通对象更适合实现哈希表。

const hashMap = new Map();
// 添加键值对
hashMap.set('key1', 'value1');
hashMap.set('key2', 'value2');
// 获取值
console.log(hashMap.get('key1')); // 输出: value1
// 删除键值对
hashMap.delete('key2');
// 检查键是否存在
console.log(hashMap.has('key1')); // 输出: true
自定义哈希函数
如果需要自定义哈希函数,可以结合 Map 或对象使用。
function customHash(key) {
let hash = 0;
for (let i = 0; i < key.length; i++) {
hash = (hash << 5) - hash + key.charCodeAt(i);
hash |= 0; // 转换为32位整数
}
return hash;
}
const hashMap = new Map();
const key = 'customKey';
const hashValue = customHash(key);
hashMap.set(hashValue, 'customValue');
console.log(hashMap.get(hashValue)); // 输出: customValue
处理哈希冲突
哈希冲突是指多个键映射到同一个哈希值的情况。可以通过链地址法(使用数组或链表存储冲突的键值对)或开放寻址法解决。
class HashTable {
constructor(size = 32) {
this.size = size;
this.buckets = Array(size).fill(null).map(() => []);
}
hash(key) {
let hash = 0;
for (let char of key) {
hash = (hash << 5) - hash + char.charCodeAt(0);
hash |= 0;
}
return hash % this.size;
}
set(key, value) {
const index = this.hash(key);
const bucket = this.buckets[index];
const found = bucket.find(item => item.key === key);
if (found) {
found.value = value;
} else {
bucket.push({ key, value });
}
}
get(key) {
const index = this.hash(key);
const bucket = this.buckets[index];
const found = bucket.find(item => item.key === key);
return found ? found.value : undefined;
}
}
const table = new HashTable();
table.set('name', 'Alice');
console.log(table.get('name')); // 输出: Alice
性能注意事项
- 对象和
Map的插入、删除和查找操作的平均时间复杂度为 O(1)。 Map支持任意类型的键(包括对象),而对象的键只能是字符串或 Symbol。Map保留了键值对的插入顺序,而对象不保证顺序。
以上方法可以根据实际需求选择适合的方式实现哈希表功能。






