微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

用Javascript实现哈希表

如何解决用Javascript实现哈希表

我无法根据我在 setter 类中的内容编写哈希类的 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,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.push([key,[value,value2]]);

致:

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

似乎给了我想要的结果

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。