能使用js为我写一个完整的例子,散列数值的组合,单个的判断。
时间: 2023-04-06 11:04:49 浏览: 51
可以的,以下是一个使用 JavaScript 实现散列数值的组合和单个判断的例子:
```javascript
// 定义一个散列函数
function hash(str) {
let hash = 0;
for (let i = 0; i < str.length; i++) {
hash = (hash << 5) - hash + str.charCodeAt(i);
hash |= 0;
}
return hash;
}
// 定义一个散列表
const hashTable = {};
// 添加散列值
hashTable[hash('apple')] = '苹果';
hashTable[hash('banana')] = '香蕉';
hashTable[hash('orange')] = '橙子';
// 判断单个值是否存在
const key = 'apple';
if (hashTable[hash(key)]) {
console.log(`${key} 存在,对应的值为 ${hashTable[hash(key)]}`);
} else {
console.log(`${key} 不存在`);
}
// 组合散列值
const combinedHash = hash('apple') + hash('banana') + hash('orange');
if (hashTable[combinedHash]) {
console.log(`组合散列值存在,对应的值为 ${hashTable[combinedHash]}`);
} else {
console.log(`组合散列值不存在`);
}
```
希望这个例子能够帮助你理解散列数值的组合和单个判断的实现。