The example in this article describes how JS custom objects implement the Map object function in Java. Share it with everyone for your reference. The specific analysis is as follows:
There are collection, Map and other object storage tool classes in Java. These objects are easy to use, but in JavaScript, you can only use Array objects.
Here I create a custom object. This object contains an array to store data. The data object is a Key, which can actually store the content!
Here for Key, you have to use the String type. Just like Java, you can perform some operations such as adding, deleting, modifying, and obtaining.
It’s very simple to use. Let me show you the tools first:
/**
* @version 1.0
* Used to implement the page Map object, the Key can only be String, the object is 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;
};
}
如果你不懂Js中对象的创建等一些基础知识,自己可以网上查一下。
// 自定义Map对象
var map = new Map();
map.put("a","a");
alert(map.get("a"));
map.put("a","b");
alert(map.get("a"));
Pop a first and then pop b , because the latter one will overwrite the previous one!
Please write down other methods yourself!
I hope this article will be helpful to everyone’s JavaScript programming design.