试图在 JS 中创建哈希 [​​=11=]...无法弄清楚如何在没有给定索引的情况下使用给定的哈希函数编写 "get" 函数

Trying to create a hash table in JS... Can't figure out how to write a "get" function with the given hash function without being given an index

所以我已经能够创建一个似乎可以正常工作的集合函数。当我尝试创建一个 'get' 函数来搜索作为参数传入的 'key' 上传递的哈希表时,问题就来了。

散列函数采用 'string' 和 'size' 参数,而不是 'key' ,就像我试图弄明白的所有示例一样。这是我得到的散列函数...

  function hashCode(string, size){
    let hash = 0;
    if (string.length == 0) return hash;
    for (let i = 0; i < string.length; i++) {
      const letter = string.charCodeAt(i);
      hash = ((hash << 5) - hash) + letter;
      hash = hash & hash; // Convert to 32bit integer
    }
    return Math.abs(hash) % size ;
  }

这是我的 'set' 'HashTable' class 函数和我写的 'set' 函数...

function HashTable() {
    this.SIZE = 16;
    this.storage = new Array(this.SIZE);
  }
  
  // stores a value in the storage array
  HashTable.prototype.set = function(key, value) {
    let index = hashCode(value, 16);
    if (!this.storage[index]) {
      this.storage[index] = [];
    }
    this.storage[index][key] = value
  };

我尝试了几种不同的方法来使 'get' 功能起作用。我尝试遍历数组并使用 .hasOwnProperty 方法,目前尝试在循环中仅使用点符号来查找 属性(如下所示)。我似乎无法让它与我列出的方法一起工作,并且想不出任何其他方法来在数组中找到 key/value 对,而不能从散列函数中获取索引。

这是我正在研究的 'get' 方法...

HashTable.prototype.get = function(key) {
    this.storage.forEach((kvpair) => {
        if (kvpair.key) {
            return kvpair.key
        }
    })
  };

当我像这样创建 class 的新实例时...

 let table = new HashTable;

和 运行 'set' 函数...

table.set('key','value');

和console.log 'table'我明白了...

HashTable {SIZE: 16, storage: [ , [ key: 'value' ], , , , , , , , , , , , , , ] }

当我尝试 运行 我的 'get' 方法时...

table.get('key')

未定义被记录到控制台...

我只是不确定如何使这个 'get' 函数在没有索引的情况下工作...我显然没有用我的循环和点符号正确检索值...

任何提示、技巧、想法、提示或帮助将不胜感激!

我稍微修改了你的 get 函数:

HashTable.prototype.get = function(key) {    
    var value = null
    this.storage.forEach((kvpair) => {
            if (kvpair.key) {
              value = kvpair.key;
            }
        })
    return value;
    };

我不知道为什么这行得通而你的代码却不行...

谁能解释一下,谢谢

问题是您的 get 方法没有 return 语句。确实,传递给 forEach 的回调有一个 return 语句,但它定义了回调的 return 值,而不是 get 方法的值。

此外,return在 forEach 回调中输入值是无用的:returned 值无处可去。 forEach 不对其进行任何操作。

相反,我建议使用 find:

HashTable.prototype.get = function(key) {
    return this.storage.find(kvpair => kvpair.key)?.key;
};

这也将遍历 key/value 对,但 find 旨在在回调 return 为真值时立即停止迭代。由于您希望 key 是真实的,因此在该回调中 return kvpair.key 就足够了。然后 find 将 return kvpair ,其中 key 为真。然后剩下的就是再次抢key属性.

?. 运算符将确保如果找不到密钥,find 将 return undefined 不会发生错误,但是 undefined 将被 returned 而不是在 undefined.

上访问 属性