This article illustrates the method of realizing the function of the map object in Java by the JS custom object. Share to everyone for your reference. The specific analysis is as follows:
In Java, there are collections, maps, and other object storage utility classes, which 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 the data, the data object is a key, can actually store the content!
Here key, you want to use string type, like Java, you can do some additions, deletions, modifications, get the operation.
Use is very simple, I first put the tool class for everyone to look at:
Copy Code code as follows:
/**
* @version 1.0
* Used to implement the page Map object, the key can only be string, object arbitrary
*/
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 the creation of JS objects and other basic knowledge, you can check online.
Copy Code code as follows:
Customizing a Map Object
var map = new map ();
Map.put ("A", "a");
Alert (Map.get ("a"));
Map.put ("A", "B");
Alert (Map.get ("a"));
First eject a behind a B, because the back will cover the front!
Other ways you write and write yourself look!
I hope this article will help you with your JavaScript programming.