在 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>