This article describes the method of implementing the functions of Map objects in Java by custom objects in JS. Share it for your reference. The specific analysis is as follows:
There are object storage tool classes such as collections and Map in Java. 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 that can be actually stored!
Here, you want to use the String type. Like Java, you can do some operations that add, delete, modify, and obtain.
It's very simple to use, I'll show you the tool class first:
Copy the code as follows:/**
* @version 1.0
* Used to implement page map object, the Key can only be a String, the object can be 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 don't understand some basic knowledge such as creating objects in Js, you can check it online.
Copy the code as follows:// Custom Map object
var map = new Map();
map.put("a","a");
alert(map.get("a"));
map.put("a","b");
alert(map.get("a"));
First pop a and then pop b, because the one behind will cover the one in front!
Everyone writes other methods for yourself!
I hope this article will be helpful to everyone's JavaScript programming.