es6的map的键可以是任意的数据结构,并且不重复。
那么map的底层原理是啥呢?
map利用链表,hash的思想来实现。
首先,map可以实现删除,而且删除的数据可以是中间的值。而链表的优势就是在中间的任意位置添加,删除元素都非常快,不需要移动其他元素,直接改变指针的指向就可以。
。
而在存储数据很多的情况下,会导致链条过长,导致查找效率慢,所以我们可以创建一个桶(存储对象的容器),根据hash(把散列的值通过算法变成固定的某值)来平局分配数据,防止链条过长。
如下图:桶里面有3个位置,每一个位置都是一个对象,通过next属性指向下一个对象来把没有关联的对象联到一起。
把map属性值和属性名都存到对象的值里。
function mymap1(){
this.init();
}
mymap1.prototype.init = function(){
this.tong = new Array(8);
for(let i=0;i<8;i++){
this.tong[i] = new Object();
this.tong[i].next = null;
}
};
mymap1.prototype.set = function(key,value){
let index = this.hash(key);
let temp = this.tong[index];
while(temp.next){
if(temp.next.key == key){
temp.next.value = value;return;
}else{
temp = temp.next;
}
}
temp.next = {
key:key,value:value,next:null
}
};
mymap1.prototype.get = function(key){
let index = this.hash(key);
let temp = this.tong[index];
while(temp){
if(temp.key == key){
return temp.value;
}else{
temp = temp.next;
}
}
return undefined;
};
mymap1.prototype.has = function(key){
let index = this.hash(key);
let temp = this.tong[index];
while(temp.next){
if(temp.next.key == key){
return true;
}else{
temp = temp.next;
}
}
return false;
};
mymap1.prototype.clear = function(){this.init();};
mymap1.prototype.hash = function(key)
{
let index = 0;
if(typeof key == "string"){
for(let i=0;i<3;i++){
index = index + isNaN(key.charCodeAt(i)) ?0: key.charCodeAt(i);
}
}
else if(typeof key == 'Object'){index = 0}
else if(typeof key == 'Number'){index = isNaN(key)?7:key;}
else{ index = 1;}
return index%8;
};
var map2 = new mymap1();