首页 > 解决方案 > 在Javascript中实现哈希表

问题描述

根据我在 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
}

标签: javascripthashtable

解决方案


改变:

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

至:

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

似乎给了我想要的结果


推荐阅读