js实现散
散列(哈希)的实现方法
在JavaScript中,散列通常通过对象或Map数据结构实现。以下是几种常见的散列实现方式:
使用普通对象实现散列
const hash = {};
hash['key1'] = 'value1';
hash['key2'] = 'value2';
使用Map对象实现散列
const map = new Map();
map.set('key1', 'value1');
map.set('key2', 'value2');
自定义散列函数
如果需要实现自定义的散列函数,可以使用以下方法:
function simpleHash(key, size) {
let hash = 0;
for (let i = 0; i < key.length; i++) {
hash = (hash + key.charCodeAt(i) * (i + 1)) % size;
}
return hash;
}
处理散列冲突
常见的散列冲突解决方法包括:
链地址法
class HashTable {
constructor(size) {
this.size = size;
this.buckets = Array(size).fill(null).map(() => []);
}
set(key, value) {
const index = this.hash(key);
this.buckets[index].push({key, value});
}
get(key) {
const index = this.hash(key);
return this.buckets[index].find(item => item.key === key)?.value;
}
}
开放寻址法
class HashTable {
constructor(size) {
this.size = size;
this.table = new Array(size).fill(null);
}
set(key, value) {
let index = this.hash(key);
while (this.table[index] !== null) {
index = (index + 1) % this.size;
}
this.table[index] = {key, value};
}
}
实际应用示例
统计单词频率
function wordFrequency(text) {
const freq = {};
text.split(/\s+/).forEach(word => {
freq[word] = (freq[word] || 0) + 1;
});
return freq;
}
缓存实现
function createCache() {
const cache = new Map();
return function(key, value) {
if (value !== undefined) cache.set(key, value);
return cache.get(key);
};
}
这些方法展示了JavaScript中实现散列的不同方式,可以根据具体需求选择合适的实现方案。







