当前位置:首页 > JavaScript

js 实现hashtable

2026-02-02 06:10:50JavaScript

哈希表(HashTable)的基本实现

在 JavaScript 中,哈希表可以通过对象(Object)或 Map 实现。以下是两种常见的实现方式:

使用 Object 实现哈希表

JavaScript 的对象本质上是键值对的集合,可以直接作为哈希表使用。

const hashTable = {};

// 添加键值对
hashTable['key1'] = 'value1';
hashTable['key2'] = 'value2';

// 获取值
console.log(hashTable['key1']); // 输出: value1

// 删除键值对
delete hashTable['key1'];

// 检查键是否存在
console.log('key1' in hashTable); // 输出: false

使用 Map 实现哈希表

ES6 引入的 Map 提供了更强大的哈希表功能,支持任意类型的键(包括对象)。

const hashMap = new Map();

// 添加键值对
hashMap.set('key1', 'value1');
hashMap.set('key2', 'value2');

// 获取值
console.log(hashMap.get('key1')); // 输出: value1

// 删除键值对
hashMap.delete('key1');

// 检查键是否存在
console.log(hashMap.has('key1')); // 输出: false

// 获取大小
console.log(hashMap.size); // 输出: 1

手动实现哈希表

如果需要手动实现哈希表,可以基于数组和哈希函数构建。

class HashTable {
  constructor(size = 100) {
    this.size = size;
    this.table = new Array(size).fill(null).map(() => []);
  }

  // 哈希函数(简单示例)
  _hash(key) {
    let hash = 0;
    for (let i = 0; i < key.length; i++) {
      hash += key.charCodeAt(i);
    }
    return hash % this.size;
  }

  // 添加键值对
  set(key, value) {
    const index = this._hash(key);
    const bucket = this.table[index];
    const found = bucket.find(item => item[0] === key);
    if (found) {
      found[1] = value; // 更新值
    } else {
      bucket.push([key, value]); // 添加新键值对
    }
  }

  // 获取值
  get(key) {
    const index = this._hash(key);
    const bucket = this.table[index];
    const found = bucket.find(item => item[0] === key);
    return found ? found[1] : undefined;
  }

  // 删除键值对
  delete(key) {
    const index = this._hash(key);
    const bucket = this.table[index];
    const itemIndex = bucket.findIndex(item => item[0] === key);
    if (itemIndex >= 0) {
      bucket.splice(itemIndex, 1);
      return true;
    }
    return false;
  }
}

// 使用示例
const myHashTable = new HashTable();
myHashTable.set('name', 'Alice');
console.log(myHashTable.get('name')); // 输出: Alice
myHashTable.delete('name');
console.log(myHashTable.get('name')); // 输出: undefined

哈希冲突处理

手动实现时,哈希冲突通过链地址法(每个桶是一个链表或数组)解决。其他方法包括开放寻址法(线性探测、二次探测等)。

js 实现hashtable

开放寻址法示例

class HashTableOpenAddressing {
  constructor(size = 100) {
    this.size = size;
    this.table = new Array(size).fill(null);
  }

  _hash(key) {
    let hash = 0;
    for (let i = 0; i < key.length; i++) {
      hash += key.charCodeAt(i);
    }
    return hash % this.size;
  }

  set(key, value) {
    let index = this._hash(key);
    while (this.table[index] !== null && this.table[index][0] !== key) {
      index = (index + 1) % this.size; // 线性探测
    }
    this.table[index] = [key, value];
  }

  get(key) {
    let index = this._hash(key);
    while (this.table[index] !== null) {
      if (this.table[index][0] === key) {
        return this.table[index][1];
      }
      index = (index + 1) % this.size;
    }
    return undefined;
  }
}

性能优化

  • 动态扩容:当负载因子(元素数量/桶数量)超过阈值时,扩容并重新哈希。
  • 更好的哈希函数:减少冲突概率(如使用加密哈希的简化版本)。

标签: jshashtable
分享给朋友:

相关文章

jquery.js

jquery.js

jQuery 简介 jQuery 是一个快速、简洁的 JavaScript 库,用于简化 HTML 文档遍历、事件处理、动画设计和 Ajax 交互。它的设计宗旨是“Write Less, Do Mor…

js实现倒计时

js实现倒计时

使用 setInterval 实现倒计时 通过 setInterval 定时器每秒更新剩余时间,适用于简单倒计时场景。 function countdown(seconds, callbac…

js实现复制功能

js实现复制功能

使用 document.execCommand 方法 这种方法适用于较旧的浏览器,但在现代浏览器中可能被逐步淘汰。通过创建一个临时的 textarea 元素,将文本内容放入其中,然后执行复制命令。…

js实现图片放大缩小

js实现图片放大缩小

实现图片放大缩小的基础方法 使用CSS的transform: scale()属性可以快速实现图片的放大缩小效果。通过JavaScript动态修改该属性值: const img = document.…

js实现vr

js实现vr

使用WebXR API实现VR体验 WebXR是浏览器中实现VR和AR体验的标准API,它取代了早期的WebVR。现代浏览器如Chrome、Edge和Firefox已支持WebXR。 // 初始化W…

链表实现js

链表实现js

链表的基本概念 链表是一种线性数据结构,由一系列节点组成,每个节点包含数据和一个指向下一个节点的指针(单向链表)或两个指针(双向链表)。与数组不同,链表在内存中非连续存储,插入和删除操作更高效,但随机…