数据结构 - 如何在javascript中实现哈希表(包括关联列表)?

data structure - how to implement hash tables (including association lists) in javascript?

我正在做散列table/数据结构练习,但不是很了解。 每个数据都必须是列表 'List' 的一个实例,并且使用散列函数,我需要将键/值对添加到正确的列表中,并 return 基于它们的键的项目。 由于我到目前为止所尝试的方法不起作用,因此我将非常感谢任何帮助或解释为什么我到目前为止所尝试的方法不起作用!谢谢!

function List () {
  this.head=null;
}
function ListN (key, value, next) {
  this.key = key;
  this.value = value;
  this.next = next;
}
List.prototype.set = function (key, value) {
 var newNode=new ListN(key, value, this.head);
  this.head=newNode;
};

List.prototype.get = function (key) {
  var node = this.head;
    while (node) {
       if (node.key === key) {
        return node.value;
       }
        node = node.next;
    }
};
  smallList = new List();

function HashT () {
  this.data = Array(30);
}

HashT.prototype.set = function (key, value) {
  var index=hash(key);
  if (!this.data[index]) {
    this.data[index]=new List();
  }

  this.data[index].set({key:key, value:value});
};

HashT.prototype.get = function (key) {
var index=hash(key);
return this.data[index];

};

问题很简单,你的错误在这里:

this.data[index].set({key:key, value:value});

需要改为

this.data[index].set(key, value);

在您的 HashT.prototype.get 中,return 语句需要是:

return this.data[index].get(key);