JavaScript is not as handy in programming as Java, providing a lot of APIs for development to call directly, but the bottom layer also encapsulates a lot of tools for developers to write methods to implement,
Take map For example, write simple additions and deletions to simulate the map in Java:
function Map () {
var obj = {}; Create an Object
To bind a value to a map
This.put = function (key,value) {
Obj[key] = value;
}
Get the number of maps
var count = 0;
This.size = function () {
var count = 0;
for (var i in obj) {
Count + +;
}
return count;
}
Get value based on key (very common, used today when writing Java)
This.get = function (key) {
if (Obj[key] | | obj[key] = = 0 | | obj[key] = = = False) {
return Obj[key];
}else{
return null;
}
}
removing values
This.remove = function (key) {
if (Obj[key] | | obj[key] = = 0 | | obj[key] = = = False) {
Delete Obj[key];
}
}
The key (value) that traverses the map;
This.foreach = function (fn) {//FN callback function
for (var i in obj) {
FN (I,obj[i]);
}
}
}
var m = new Map (); Instantiate a map
M.put ("001", false); To add a key value to a map
M.put ("002", true);
M.put ("003", "sz");
To test
Alert (M.size ());
Alert (M.get ("003"));
Alert (M.remove ("001"));
M.foreach (function (key,value) {
Alert (key + ":" + value);
})
Javascript_object (based on map exercises)