一、Map的基本使用
1. 基本使用
// Map 是一个构造函数
let map = new Map();
// k,v 可以是任意数据类型
// 设置
map.set(1,'a')
map.set(1,'b') // 相同key覆盖,去重
map.set({ name:'ls' },'12')
console.log(map); // { 1 => 'b', {...} => '12' }
// 获取
map.get(1); // b
// 判断
map.has(1); //true
// 删除
map.delete(1);
// 遍历
for(let entries of map){ //entries是[k,v]的数组
console.log(entries); //[1, 'b'] [{...}, '12']
}
2. 实际开发中,Map等新生数据结构只在js中存在,不利于传输,因此需要我们自己对其进行转化
在js中 Map,Set,Array,Object 之间的相互转换:
(1)Object.entries获取对象的键值对
(2)Object.FromEntries把键值对列表转成对象
(3)Object.entries和Object.fromEntries之间是可逆的。
// 1. Object转Map
let obj = {foo:'hello',bar:100};
let map = newap(Object.entries(obj));
console.log(map)
// 2. Map转Object
let map = new Map([['foo','hello'],['bar',100]]);
let obj = Object.fromEntries(map);
console.log(obj);
// 3. Object转Array
let obj = {'foo':'hello','bar':100};
let arr = Object.entries(obj);
console.log(arr);
// 4. Array转成Object
let arr = [['foo','hello'],['bar',100]];
let obj = Object.fromEntries(arr);
console.log(obj);
// 5. Array转Set
let arr = [['foo','hello'],['bar',100]];
let set = new Set(arr);
console.log(set)
3、Map对比
功能上对比:Map具有比Object更多的方法、去重、key引用数据类型
性能上对比:
数组查找快,链表增删快,Map结合数组 + 链表优势实现高性能增删改查(外层数组,里面是链表)
二、手写Map
let count = 8;
// 8个元素的数组,以byte最小单位
function MyMap(){
//构造器
this.initStore();
}
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;
}
// set方法
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){
// 覆盖
return queue.next.value = v;
} else {
// 下一个
queue = queue.next;
}
}
// 第一次执行到这里,就是第一个数据 k:1
// 第二次以后执行到这里,就是末尾的一个
queue.next = {
next:null,
key:k,
value:v
}
}
// get方法
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;
}
// has方法
MyMap.prototype.has = function(k){
return this.get(k) !== undefined;
}
let m = new 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')
console.log(m);
console.log(m.get(1),m.set(9,'h'),m.has(3));