This article mainly introduces how to implement the Map object function in Java by using JS custom objects. It can implement functions such as adding, deleting, modifying, and querying Map objects in Java and has some reference value, for more information about how to implement the Map object function in Java, see the examples in this article. Share it with you for your reference. The specific analysis is as follows:
Java has collection, Map, and Other Object Storage tools. These objects are easy to use, but in JavaScript, you can only use Array objects.
Here I create a custom object, which contains an array to store data. The data object is a Key and can actually store content!
Here, you need to use the String type. Like Java, you can add, delete, modify, and obtain some operations.
It's easy to use. Let's take a look at the tool class:
The Code is as follows:
/**
* @ Version 1.0
* It is used to implement the PAGE Map object. The Key can only be a String and the object is random.
*/
Var Map = function (){
This. _ entrys = new Array ();
This. put = function (key, value ){
If (key = null | key = undefined ){
Return;
}
Var index = this. _ getIndex (key );
If (index =-1 ){
Var entry = new Object ();
Entry. key = key;
Entry. value = value;
This. _ entrys [this. _ entrys. length] = entry;
} Else {
This. _ entrys [index]. value = value;
}
};
This. get = function (key ){
Var index = this. _ getIndex (key );
Return (index! =-1 )? This. _ entrys [index]. value: null;
};
This. remove = function (key ){
Var index = this. _ getIndex (key );
If (index! =-1 ){
This. _ entrys. splice (index, 1 );
}
};
This. clear = function (){
This. _ entrys. length = 0 ;;
};
This. contains = function (key ){
Var index = this. _ getIndex (key );
Return (index! =-1 )? True: false;
};
This. getCount = function (){
Return this. _ entrys. length;
};
This. getEntrys = function (){
Return this. _ entrys;
};
This. _ getIndex = function (key ){
If (key = null | key = undefined ){
Return-1;
}
Var _ length = this. _ entrys. length;
For (var I = 0; I <_ length; I ++ ){
Var entry = this. _ entrys [I];
If (entry = null | entry = undefined ){
Continue;
}
If (entry. key = key) {// equal
Return I;
}
}
Return-1;
};
}
If you do not understand basic knowledge about object creation in Js, you can check it online.
The Code is as follows:
// Custom Map object
Var map = new Map ();
Map. put ("a", "");
Alert (map. get (""));
Map. put ("a", "B ");
Alert (map. get (""));
First, pop up a and then pop up B, because the latter will overwrite the previous one!
For other methods, write them by yourself!
I hope this article will help you design javascript programs.