仿写es6的 new Map():
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<script>
let Map = (function(){
let symbol = Symbol();
return class{
constructor(){
this[symbol] = [];
}
set(key,value){
for(let i=0,len=this.size();i<len;i++){
let item = this[symbol][i];
if(item[0] === key){
item[1] = value
return true;
}
}
this[symbol].push([key,value]);
return true;
}
get(key){
for(let i=0,len=this.size();i<len;i++){
let item = this[symbol][i];
if(item[0] === key){
return item;
}
}
return undefined;
}
delete(key){
for(let i=0,len=this.size();i<len;i++){
let item = this[symbol][i];
if(item[0] === key){
this[symbol].splice(i,1);
return true;
}
}
return true;
}
has(key){
this[symbol].forEach(item=>{
if(item[0] === key){
return true;
}
});
return false;
}
size(){
return this[symbol].length;
}
}
})();
let map = new Map();
map.set('小米',"男");
map.set('奇奇',"女");
map.set('派大星',"男");
map.set('海绵宝宝',"女");
map.set('谢老板',"男");
map.set('海绵宝宝','男');
console.log(map);
console.log(map.has('章鱼哥'));
console.log(map.set('章鱼哥','男'));
console.log(map.has('章鱼哥'));
console.log(map.size());
console.log(map.delete('章鱼哥'));
console.log(map.size());
console.log(map);
</script>
</body>
</html>