js hasmap实现
HashMap 的 JavaScript 实现
JavaScript 中没有内置的 HashMap 数据结构,但可以通过对象(Object)或 Map 类来实现类似功能。以下是两种实现方式的具体方法。
使用 Object 实现 HashMap
Object 的键值对特性可以模拟 HashMap 的基本功能。需要注意键会被自动转换为字符串。

const hashMap = {};
// 添加键值对
hashMap['key1'] = 'value1';
hashMap['key2'] = 'value2';
// 获取值
console.log(hashMap['key1']); // 输出: value1
// 删除键值对
delete hashMap['key1'];
// 检查键是否存在
console.log('key1' in hashMap); // 输出: false
使用 Map 类实现 HashMap
ES6 引入的 Map 类提供了更完整的 HashMap 功能,支持任意类型的键,并保留了插入顺序。

const hashMap = new Map();
// 添加键值对
hashMap.set('key1', 'value1');
hashMap.set(1, 'value2'); // 键可以是任意类型
// 获取值
console.log(hashMap.get('key1')); // 输出: value1
// 删除键值对
hashMap.delete('key1');
// 检查键是否存在
console.log(hashMap.has('key1')); // 输出: false
// 获取大小
console.log(hashMap.size); // 输出: 1
自定义 HashMap 实现
如果需要完全自定义 HashMap,可以基于数组和哈希函数实现。以下是一个简单示例:
class HashMap {
constructor() {
this.buckets = new Array(16).fill(null).map(() => []);
this.size = 0;
}
_hash(key) {
let hash = 0;
for (let i = 0; i < key.length; i++) {
hash = (hash << 5) - hash + key.charCodeAt(i);
hash |= 0; // 转换为32位整数
}
return Math.abs(hash) % this.buckets.length;
}
set(key, value) {
const index = this._hash(key);
const bucket = this.buckets[index];
for (let i = 0; i < bucket.length; i++) {
if (bucket[i][0] === key) {
bucket[i][1] = value;
return;
}
}
bucket.push([key, value]);
this.size++;
}
get(key) {
const index = this._hash(key);
const bucket = this.buckets[index];
for (let i = 0; i < bucket.length; i++) {
if (bucket[i][0] === key) {
return bucket[i][1];
}
}
return undefined;
}
delete(key) {
const index = this._hash(key);
const bucket = this.buckets[index];
for (let i = 0; i < bucket.length; i++) {
if (bucket[i][0] === key) {
bucket.splice(i, 1);
this.size--;
return true;
}
}
return false;
}
has(key) {
return this.get(key) !== undefined;
}
}
// 使用示例
const map = new HashMap();
map.set('name', 'Alice');
console.log(map.get('name')); // 输出: Alice
性能优化考虑
当自定义 HashMap 时,需要考虑以下优化点:
- 动态扩容:当元素数量超过容量的某个比例时,扩展桶数组大小并重新哈希所有元素
- 冲突处理:使用更好的冲突处理策略,如开放寻址法或更高效的链表结构
- 哈希函数:选择分布均匀的哈希函数减少冲突
对于大多数应用场景,直接使用 JavaScript 内置的 Map 类是最佳选择,因为它已经优化了这些方面。






