【问题标题】:Implement Hash table in Javascript在Javascript中实现哈希表
【发布时间】:2021-01-26 07:54:13
【问题描述】:

我无法根据我在 setter 类中的内容编写我的 hash 类的 getter 方法。

我得到的错误是:error: Uncaught TypeError: Cannot read property '1' of undefined

setItem = (key, value, value2) => {
    const idx = HashStringToInt(key, this.table.length);
    if (this.table[idx]) {
        this.table.push([key,[value, value2]]);
    } else {
        this.table[idx] = [[key, [value, value2]]]
    }        
}

getItem = key => {
    const idx = HashStringToInt(key, this.table.length);

    if (!this.table[idx]) {
        return null;
    }
    return this.table[idx].find(x => x[0] === key)[1]; //this doesn't work
}

【问题讨论】:

  • 如果您将this.table.length 传递给您的散列函数并且您不断更改长度,那么您希望在添加项目之前和之后收到相同的散列值吗?跨度>
  • 我明白你在说什么,但是我怎么能写这个基本上有一个键去两个值 a = b,c ?
  • 如果您希望每个键有两个值,那么存储两个项目数组的沼泽标准哈希表似乎就足够了。这里的问题不在于值的数量,而是散列不稳定 - 在您推送到数组之后,任何未来的散列重新计算都将采用数组的新长度。我不知道您的散列实现,但似乎合理的假设是 HashStringToInt("foo", 1)HashStringToint("foo", 2) 会产生不同的结果。您可以通过使用恒定大小的数组来解决这个问题,因此相同键的哈希标识是稳定的。
  • 除了散列问题之外,setItem 中的if 语句不是翻转了吗?如果给定键存在,则将新项推送到数组中,如果不存在,则覆盖键。
  • 感谢您的意见,但我现在似乎已经完成了我想做的事情

标签: javascript hashtable


【解决方案1】:

变化:

this.table.push([key,[value, value2]]);

收件人:

this.table[idx].push([key,[value, value2]]);

似乎给了我想要的结果

【讨论】:

    猜你喜欢
    • 2016-05-17
    • 2020-12-30
    • 2016-03-25
    • 2011-10-14
    • 2011-09-15
    • 2015-02-25
    • 2012-05-27
    • 2017-03-20
    相关资源
    最近更新 更多