js手写原生map

文章介绍了JavaScript中的Map数据结构,它用于存储键值对。文中以一个简单的MyMap类为例,展示了如何使用哈希表作为底层实现,包括set、get和has等基本操作。通过这个例子,读者可以理解Map如何通过哈希函数将键映射到数组索引来快速访问数据。
摘要由CSDN通过智能技术生成

 

在 JavaScript 中,Map 是一种集合数据结构,它能够存储键值对。Map 的底层实现通常是依赖于哈希表(Hash Table)或红黑树等高效的数据结构。这里我将简要介绍哈希表作为底层实现的原理。

哈希表是一种基于数组的数据结构,它通过哈希函数将键转化为数组的索引。

底层map实现代码如下:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <script>
        // hash
      let count = 8;
    //   自定义map
      function MyMap() {
        this.initStore();
      }
    //   hash
      MyMap.prototype.initStore = function () {
        this.store = new Array(count);
        for (let i = 0; i < this.store.length; i++) {
          this.store[i] = {
            next: null,
          };
        }
      };
      MyMap.prototype.hash = function (k) {
        return k % count;
      };

      MyMap.prototype.set = function (k, v) {
        // 通过key计算余数8,取得房间号
        let roomIndex = this.hash(k);
        // 取出链表头
        let queue = this.store[roomIndex];
        // 找元素
        while (queue.next) {
            // 不断的向下找
          if (queue.next.key === k) {
            // 覆盖
            queue.next.value = v;
          } else {
            // 下一个
            queue = queue.next;
          }
        }
        // 第一次执行到这里就是第一个数据
        // 第二次执行到这里就是末尾的一个
        queue.next = {
          next: null,
          key: k,
          value: v,
        };
      };

      MyMap.prototype.get = function (k) {
        let roomIndex=this.hash(k)
        let queue=this.store[roomIndex]
        queue=queue.next
        while(queue){
            if(queue.key===k){
                return queue.value
            }else{
                // 指针下移
                queue=queue.next
            }
        }
        return undefined//没有找到
      };
      MyMap.prototype.has = function (k) {
        return this.get(k)!==undefined
      };

      let m = new MyMap();
    //   调用MyMap
      m.set(1, "a");
      m.set(2, "b");
      m.set(3, "c");
      m.set(4, "d");
      m.set(5, "e");
      m.set(6, "f");
      m.set(7, "g");
      m.set(8, "h");
      m.set(9, "i");
      console.log(m,m.get(1), m.has(9));
      console.log(m.get(2));
      console.log(m.get(3));
      console.log(m.get(4));
      console.log(m.has(6));
    </script>
  </body>
</html>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值