使用 Javascript 创建哈希表
让我们设置一个简单的类,我们将在其中定义所有这些方法。我们创建一个容器对象来存储哈希表并创建一个 display 函数来显示表。注意,对于冲突解决,我们将使用链接。
display 函数获取表中的每个条目(经过哈希处理的值),并打印与之关联的所有对。
示例
我们还将在原型中创建一个新类来存储键值对。
class HashTable {
constructor() {
this.container = [];
// Populate the container with empty arrays
// which can be used to add more elements in
// cases of collisions
for(let i=0; i < 11; i ++ ) {
this.container.push([]);
}
display() {
this.container.forEach((value, index) => {
let chain = value
.map(({ key, value }) => `{ ${key}: ${value} }`)
.join(" --> ");
console.log(`${index}: ${chain}`);
});
}
hash(key) {
return key % 11;
}
}
HashTable.prototype.KVPair = class {
constructor(key, value) {
this.key = key;
this.value = value;
}
}
}我们在 display 方法中使用了一些高级功能,如解构。这有助于避免样板代码。
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP