You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript自定义HashTable实现修改值不生效问题排查求助

问题根源

你代码的bug出在set方法的重复键更新逻辑中:

  • 代码行arr[1] === value使用的是相等比较运算符,仅会返回布尔判断结果,不会对arr[1]执行赋值操作,因此旧值从未被修改。
  • 同时你定义的const arr1 = arr[1]没有任何实际作用,属于冗余代码可以直接删除,另外if (Array.isArray(this.data[address]))的判断也属于多余逻辑,前面的初始化逻辑已经保证该位置一定是数组。
修复后的完整代码
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 arr of this.data[address]) {
      if (arr[0] === key) {
        // 把双等号改为单等号执行赋值
        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")); // 正确输出4
myHashTable.set("peach", 9);
console.log(myHashTable.get("peach")); // 输出9
myHashTable.set("apple", 2);
console.log(myHashTable.get("apple")); // 输出2

内容的提问来源于stack exchange,提问作者Hayk

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 20:24:04