1. HashMap原理
- HashMap中,采用数组+链表的方式来实现对数据的储存(因为数组是查找快,增删满;链表是查找慢,增删快)
- 简单的用图形表示一下HashMap实现原理

2. 使用JS实现一个简单的HashMap(这里用取余代替Hash算法)
2.1 规定HashMap存储长度为8,并定义MyHashMap函数
const mapSize = 8;
function MyHashMap() {
this.initStore();
}
2.2 定义初始化链表的函数
MyHashMap.prototype.initStore = function () {
this.store = new Array(mapSize)
for (let i = 0; i < mapSize; i++) {
this.store[i] = {
next: null
};
}
}
2.3 定义自己的Hash算法
MyHashMap.prototype.hash = function (n) {
return n % mapSize;
}
2.4 定义获取HashMap元素值的方法
MyHashMap.prototype.get = function (key) {
let index = this.hash(key);
let queue = this.store[index];
while (queue) {
if (queue.key === key) {
return queue.val;
} else {
queue = queue.next;
}
}
return undefined;
}
2.5 定义判断HashMap是否已经存在某元素的函数
MyHashMap.prototype.has = function (key) {
return !!this.get(key)
}
2.6 定义存储数据的函数
MyHashMap.prototype.set = function (key, val) {
let index = this.hash(key);
let queue = this.store[index];
while (queue.next) {
if (queue.next.key === key) {
queue.next.val = val;
return;
} else {
queue = queue.next;
}
}
queue.next = {
next: null,
key,
val
}
}