Este artículo describe el método para implementar las funciones de los objetos de mapa en Java por objetos personalizados en JS. Compártelo para su referencia. El análisis específico es el siguiente:
Hay clases de herramientas de almacenamiento de objetos, como colecciones y mapa en Java. Estos objetos son fáciles de usar, pero en JavaScript, solo puede usar objetos de matriz.
Aquí creo un objeto personalizado, que contiene una matriz para almacenar datos. ¡El objeto de datos es una clave que realmente se puede almacenar!
Aquí, desea usar el tipo de cadena. Al igual que Java, puede hacer algunas operaciones que agregan, eliminen, modifiquen y obtengan.
Es muy simple de usar, te mostraré la clase de herramientas primero:
Copie el código de la siguiente manera:/**
* @version 1.0
* Utilizado para implementar el objeto de mapa de página, la clave solo puede ser una cadena, el objeto puede ser arbitrario
*/
var map = function () {
this._entrys = new Array ();
this.put = function (clave, valor) {
if (key == null || key == Undefined) {
devolver;
}
índice var = this._getIndex (clave);
if (index == -1) {
VAR entry = new Object ();
Entry.Key = Key;
entry.Value = Value;
this._entrys [this._entrys.length] = entry;
}demás{
this._entrys [índice] .value = valor;
}
};
this.get = function (key) {
índice var = this._getIndex (clave);
return (índice! = -1)? this._entrys [índice] .value: null;
};
this.remove = function (key) {
índice var = this._getIndex (clave);
if (index! = -1) {
this._entrys.splice (índice, 1);
}
};
this.clear = function () {
this._entrys.length = 0 ;;
};
this.contains = function (key) {
índice var = this._getIndex (clave);
return (índice! = -1)? verdadero: falso;
};
this.getCount = function () {
devolver esto._entrys.length;
};
this.getEntrys = function () {
devolver esto._Entrys;
};
this._getIndex = function (key) {
if (key == null || key == Undefined) {
regreso -1;
}
var _length = this._entrys.length;
para (var i = 0; i <_length; i ++) {
entry var = this._entrys [i];
if (entry == null || entry == Undefined) {
continuar;
}
if (entry.key === key) {// igual
regresar i;
}
}
regreso -1;
};
}
Si no comprende algunos conocimientos básicos, como crear objetos en JS, puede verificarlo en línea.
Copie el código de la siguiente manera: // Objeto de mapa personalizado
var map = new Map ();
map.put ("A", "A");
alerta (map.get ("a"));
map.put ("a", "b");
alerta (map.get ("a"));
¡Primero establezca A y luego Pop B, porque el que está detrás cubrirá el delante!
¡Todos escriben otros métodos para usted!
Espero que este artículo sea útil para la programación de JavaScript de todos.