Look directly at the code:
1 //simulating a Map object2 functionMap () {3 4 //declaring a container5 varContainer={};6 7 //define a put method to store values in the container8 This. put=function(key,value) {9container[key]=value;Ten } One A //get value from key - This. get=function(key) { - if(Container[key] | | container[key]===0 | | container[key]===false){ the returnContainer[key] -}Else{ - return NULL; - } + } - + //gets the number of key-value pairs stored in the map A This. size=function(){ at varCount=0; - //Traversing Object Properties - for(varattrinchcontainer) { -count++; - } - returncount; in } - to //traverse the map and pass in a callback function with 2 parameters, one receiving key, one receiving value + This. each=function(callback) { - for(varattrinchcontainer) { the callback (attr,container[attr]); * } $ }Panax Notoginseng - //Delete data from map the This. remove=function(key) { + DeleteContainer[key]; A } the}
Code test:
1 //using put to store values2 varmap=NewMap ();3 4Map.put ("name", "Caoyc");5Map.put ("Age", 25);6Map.put ("Phone", "13700000000");7 8 //get value by Get9document.write ("1: Get Value by Get method <br/>"); Tendocument.write ("Name:" +map.get ("name")); Onedocument.write ("); A - //gets the number of key-value pairs stored in the map -document.write ("2: Get the value of a key value pair in a map <br/>"); thedocument.write ("Size:" +map.size ()); -document.write ("); - - //using callback functions to traverse a map +document.write ("3: Traversing map<br/> using callback functions")); -Map.each (function(key,value) { +document.write (key+ ":" +value); Adocument.write ("<br/>"); at }); -document.write ("); - - //Delete data using remove -document.write ("4: Delete data using remove <br/>"); -Map.Remove ("name"); indocument.write ("Traverse map<br/> again after deletion"); -Map.each (function(key,value) { todocument.write (key+ ":" +value); +document.write ("<br/>"); - }); thedocument.write ("Final output Result:
A JavaScript custom object to emulate a map in Java