JavaScript simulates implementing a map in the Java language
Implementation code:
<! DOCTYPE html>
<meta charset= "UTF-8" >
<script type= "Text/javascript" >
Private
var obj={};//empty object container for key-value pairs
function Map ()
{
Put method
This.put=function (Key,value)
{
obj[key]=value;//bind a key-value pair to a JS object
}
Number of users to use to map the container
This.size=function ()
{
Define a variable for the number of records
var count=0;
for (var attr in obj)
{
count++;
}
return count;
}
To get the value from key
This.get=function (Key)
{
/**
Because if the variable is 0 in JS, it is represented as false in the judged condition (type auto-conversion)
*/
if (obj[key]| | obj[key]===0| | Obj[key]===false)
{
return Obj[key];
}
Else
{
return null;
}
}
Delete based on key
This.remove=function (Key)
{
if (obj[key]| | obj[key]===0| | Obj[key]===false)
{
Delete Obj[key];
}
}
Traversing elements in a map
This.eachmap=function (Fun)
{
for (var attr in obj)
{
Fun (attr,obj[attr]);
}
}
}
Simulating a map in Java
var m=new Map ();
M.put ("1", ' Xu Shouwei ');
M.put ("2", 25);
M.put ("3", true);
M.put ("4", New Date ());
Console.log (M.size ());
Console.log (M.get ("1"));
M.remove ("1");
Console.log (M.get ("1"));
M.eachmap (function (key,value) {
Console.log (key+ ":" +value)
});
</script>
<body>
</body>
JavaScript simulates implementing a map in the Java language