Js implementation of the map method sample code

  • 2020-03-30 01:18:51
  • OfStack

 
 
function Map(){ 
var struct = function(key, value) { 
this.key = key; 
this.value = value; 
}; 
//Add a map key-value pair
var put = function(key, value){ 
for (var i = 0; i < this.arr.length; i++) { 
if ( this.arr[i].key === key ) { 
this.arr[i].value = value; 
return; 
} 
}; 
this.arr[this.arr.length] = new struct(key, value); 
}; 
//Get value based on key
var get = function(key) { 
for (var i = 0; i < this.arr.length; i++) { 
if ( this.arr[i].key === key ) { 
return this.arr[i].value; 
} 
} 
return null; 
}; 
//Delete by key
var remove = function(key) { 
var v; 
for (var i = 0; i < this.arr.length; i++) { 
v = this.arr.pop(); 
if ( v.key === key ) { 
continue; 
} 
this.arr.unshift(v); 
} 
}; 
//Gets the number of map key-value pairs
var size = function() { 
return this.arr.length; 
}; 
//Determines if the map is empty
var isEmpty = function() { 
return this.arr.length <= 0; 
}; 
this.arr = new Array(); 
this.get = get; 
this.put = put; 
this.remove = remove; 
this.size = size; 
this.isEmpty = isEmpty; 
} 

Use the same method as the Map class in Java
 
<script type="text/javascript"> 
var map=new Map(); 
map.put("num",1); 
map.put("ss","wss"); 
alert(map.size()); 
alert(map.get("num")); 
paraArr.remove("num"); 
alert(map.size()); 
alert(map.get("num")); 
</script> 

Related articles: