js实现hashmap
JavaScript 实现 HashMap
在 JavaScript 中,可以使用对象(Object)或 Map 类来实现 HashMap 的功能。以下是两种实现方式的具体方法:

使用 Object 实现 HashMap
JavaScript 的对象本质上是键值对的集合,可以用于模拟 HashMap。

// 创建 HashMap
const hashMap = {};
// 添加键值对
hashMap['key1'] = 'value1';
hashMap['key2'] = 'value2';
// 获取值
const value = hashMap['key1'];
// 删除键值对
delete hashMap['key1'];
// 检查键是否存在
const hasKey = 'key1' in hashMap;
// 遍历键值对
for (const key in hashMap) {
console.log(key, hashMap[key]);
}
使用 Map 类实现 HashMap
ES6 引入了 Map 类,提供了更完善的 HashMap 功能。
// 创建 Map
const hashMap = new Map();
// 添加键值对
hashMap.set('key1', 'value1');
hashMap.set('key2', 'value2');
// 获取值
const value = hashMap.get('key1');
// 删除键值对
hashMap.delete('key1');
// 检查键是否存在
const hasKey = hashMap.has('key1');
// 遍历键值对
hashMap.forEach((value, key) => {
console.log(key, value);
});
// 获取键的数量
const size = hashMap.size;
自定义 HashMap 实现
如果需要更底层实现,可以基于数组和哈希函数构建自定义 HashMap。
class HashMap {
constructor(size = 16) {
this.buckets = new Array(size).fill(null).map(() => []);
this.size = size;
}
// 哈希函数
hash(key) {
let hashCode = 0;
for (let i = 0; i < key.length; i++) {
hashCode += key.charCodeAt(i);
}
return hashCode % 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;
}
// 删除键值对
delete(key) {
const index = this.hash(key);
const bucket = this.buckets[index];
const itemIndex = bucket.findIndex(item => item.key === key);
if (itemIndex >= 0) {
bucket.splice(itemIndex, 1);
return true;
}
return false;
}
// 检查键是否存在
has(key) {
const index = this.hash(key);
const bucket = this.buckets[index];
return bucket.some(item => item.key === key);
}
}
// 使用示例
const map = new HashMap();
map.set('name', 'Alice');
console.log(map.get('name')); // Alice
性能比较
- Object:简单易用,但键只能是字符串或 Symbol。
- Map:支持任意类型键,提供更丰富的方法。
- 自定义实现:灵活性高,但需要手动处理冲突和扩容。
根据具体需求选择合适的实现方式。






