我對編程相當愚蠢。我想在 javascript 中實作一個簡單的哈希表(用于教育目的)。一切正常,除非當我嘗試覆寫某個值時,它保留了以前的值。例如,當我嘗試 hashTable.set(cherry, 100),然后 hashTable.set(cherry, 4) 然后 hashTable.get(cherry) 給我 100 而不是 4。我試過用除錯器檢查它,但轉如果您公平,除錯器將無濟于事愚蠢的編程新手。代碼如下:
class HashTable {
constructor(size) {
this.data = new Array(size);
}
_hash(key) {
let hash = 0;
for (let i = 0; i < key.length; i ) {
hash = (hash key.charCodeAt(i) * i) % this.data.length;
}
return hash;
}
set(key, value) {
const address = this._hash(key);
if (!this.data[address]) {
this.data[address] = [];
}
if (Array.isArray(this.data[address])) {
for (let arr of this.data[address].values()) {
if (arr[0] === key) {
const arr1 = arr[1];
arr[1] === value;
return;
}
}
}
this.data[address].push([key, value]);
}
get(key) {
const address = this._hash(key);
const currentNode = this.data[address];
if (currentNode) {
for (let arr of currentNode) {
if (arr[0] === key) {
return arr[1];
}
}
}
return undefined;
}
}
const myHashTable = new HashTable(2);
myHashTable.set("cherry", 100);
myHashTable.set("cherry", 4);
console.log(myHashTable.get("cherry")); // returns 100 instead of 4
myHashTable.set("peach", 9);
console.log(myHashTable.get("peach"));
myHashTable.set("apple", 2);
console.log(myHashTable.get("apple"));
uj5u.com熱心網友回復:
class HashTable {
constructor(size) {
this.data = new Array(size);
}
_hash(key) {
let hash = 0;
for (let i = 0; i < key.length; i ) {
hash = (hash key.charCodeAt(i) * i) % this.data.length;
}
return hash;
}
set(key, value) {
const address = this._hash(key);
if (!this.data[address]) {
this.data[address] = [];
}
for (let el of this.data[address]) {
if (el[0] === key) {
el[1] = value;
return;
}
}
this.data[address].push([key, value]);
}
get(key) {
const address = this._hash(key);
const currentNode = this.data[address];
if (currentNode) {
for (let arr of currentNode) {
if (arr[0] === key) {
return arr[1];
}
}
}
return undefined;
}
}
const myHashTable = new HashTable(2);
myHashTable.set("cherry", 100);
myHashTable.set("cherry", 4);
console.log(myHashTable.get("cherry")); // returns 100 instead of 4
myHashTable.set("peach", 9);
console.log(myHashTable.get("peach"));
myHashTable.set("apple", 2);
console.log(myHashTable.get("apple"));
你在set函式中做了一些時髦的事情。這就是我改變的。現在,它查看this.dataat的元素address并檢查第一個元素以確保鍵不相同。如果是這樣,它只會更新值并提前回傳。我想這就是你的想法。
為了使其成為更好的解決方案,我建議您向底層陣列添加容量,當密度達到某個百分比時,您可以增加底層陣列以減少哈希沖突。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/361001.html
標籤:javascript 算法 数据结构 哈希表
上一篇:條件渲染在Chrome中不起作用
下一篇:JS。如何為每個道具復制陣列物件
