哈希表javascript
时间: 2023-09-11 15:09:12 浏览: 106
在JavaScript中,没有像C#或Java那样内置的哈希表实现。但是,可以通过在JavaScript对象上封装方法来实现简单且高效的哈希表。例如,可以使用对象的属性来模拟哈希表的功能。
以下是一个示例的JavaScript哈希表的实现代码:
```javascript
function HashTable() {
// 定义属性
this.storage = [];
this.count = 0;
this.limit = 8;
}
HashTable.prototype.hashFunc = function(str, size) {
// 定义hashCode变量
var hashCode = 0;
// 先将字符串转化为数字编码
for(var i = 0; i < str.length; i++) {
hashCode = 37 * hashCode + str.charCodeAt(i);
}
// 取余操作
var index = hashCode % size;
return index;
}
// 插入&修改操作
HashTable.prototype.put = function(key, value) {
var index = this.hashFunc(key, this.limit);
var bucket = this.storage[index];
if (!bucket) {
bucket = [];
this.storage[index = bucket;
}
for (var i = 0; i < bucket.length; i++) {
var tuple = bucket[i];
if (tuple === key) {
tuple = value;
return;
}
}
bucket.push([key, value]);
this.count++;
}
// 获取哈希表的元素个数
HashTable.prototype.size = function() {
return this.count;
}
```
使用上述代码,你可以创建一个哈希表对象,并使用`put`方法插入或修改元素,使用`size`方法获取哈希表的大小。<span class="em">1</span><span class="em">2</span><span class="em">3</span>
#### 引用[.reference_title]
- *1* [javascript 哈希表(hashtable)的简单实现](https://download.csdn.net/download/weixin_38663197/13070734)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"]
- *2* *3* [哈希表(JavaScript实现)](https://blog.csdn.net/m0_48375854/article/details/121996878)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"]
[ .reference_list ]
阅读全文