Cómo crear un mapa simple usando JavaScript /jQuery [duplicar]


Esta pregunta ya tiene una respuesta aquí:

Cómo puede crear el equivalente JavaScript / jQuery de este código Java:

Map map = new HashMap(); //Doesn't not have to be a hash map, any key/value map is fine
map.put(myKey1, myObj1);
map.put(myKey2, myObj2); //Repeat n times

function Object get(k) {
    return map.get(k);
}
Author: Marcus Leon, 2010-11-22

6 answers

Editar: Respuesta desactualizada, ECMAScript 2015 (ES6) estándar javascript tiene una implementación de mapa, lea aquí para más información: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map

var map = new Object(); // or var map = {};
map[myKey1] = myObj1;
map[myKey2] = myObj2;

function get(k) {
    return map[k];
}

//map[myKey1] == get(myKey1);
 273
Author: Simen Echholt,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-07-25 01:29:43

Simplemente use objetos simples:

var map = { key1: "value1", key2: "value2" }
function get(k){
  return map[k];
}
 67
Author: Simon,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-02-27 19:24:04
function Map() {
    this.keys = new Array();
    this.data = new Object();

    this.put = function (key, value) {
        if (this.data[key] == null) {
            this.keys.push(key);
        }
        this.data[key] = value;
    };

    this.get = function (key) {
        return this.data[key];
    };

    this.remove = function (key) {
        this.keys.remove(key);
        this.data[key] = null;
    };

    this.each = function (fn) {
        if (typeof fn != 'function') {
            return;
        }
        var len = this.keys.length;
        for (var i = 0; i < len; i++) {
            var k = this.keys[i];
            fn(k, this.data[k], i);
        }
    };

    this.entrys = function () {
        var len = this.keys.length;
        var entrys = new Array(len);
        for (var i = 0; i < len; i++) {
            entrys[i] = {
                key: this.keys[i],
                value: this.data[i]
            };
        }
        return entrys;
    };

    this.isEmpty = function () {
        return this.keys.length == 0;
    };

    this.size = function () {
        return this.keys.length;
    };
}
 23
Author: Jade,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-04-13 19:13:18

Esta es una vieja pregunta, pero debido a que las respuestas existentes podrían ser muy peligrosas, quería dejar esta respuesta para futuras personas que podrían tropezar aquí...

Las respuestas basadas en el uso de un Objeto como un HashMap se rompen y pueden causar consecuencias extremadamente desagradables si se utiliza cualquier otra cosa que no sea una cadena como clave. El problema es que las propiedades del objeto se coaccionan a Cadenas usando el .método toString. Esto puede llevar a la siguiente maldad:

function MyObject(name) {
  this.name = name;
};
var key1 = new MyObject("one");
var key2 = new MyObject("two");

var map = {};
map[key1] = 1;
map[key2] = 2;

Si si esperara que el Objeto se comportara de la misma manera que un mapa Java aquí, estaría bastante molesto al descubrir que el mapa solo contiene una entrada con la clave de cadena [object Object]:

> JSON.stringify(map);
{"[object Object]": 2}

Esto es claramente no un reemplazo para el HashMap de Java. Curiosamente, dada su edad, Javascript no tiene actualmente un objeto de mapa de propósito general. Hay esperanza en el horizonte, sin embargo: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map aunque un vistazo a la tabla de compatibilidad del navegador mostrará que esto no está listo para usarse en aplicaciones web de propósito general todavía.

Mientras tanto, lo mejor que puedes hacer es:

  • Utiliza deliberadamente cadenas como claves. Es decir, usar cadenas explícitas como claves en lugar de confiar en las implícitas .toString de las llaves que utiliza.
  • Asegúrese de que los objetos que está utilizando como claves tienen un bien definido .toString () método que se adapte a su comprensión de la unicidad para estos objeto.
  • Si no puede/no quiere cambiar el .toString de los objetos clave, al almacenar y recuperar las entradas, convertir los objetos a una cadena que representa su comprensión de la unicidad. Por ejemplo, map[toUniqueString(key1)] = 1

A veces, sin embargo, eso no es posible. Si desea asignar datos basados, por ejemplo, en objetos de archivo, no hay una forma fiable de hacerlo porque los atributos que expone el objeto de archivo no son suficientes para garantizar su singularidad. (Usted puede tener dos Archivos objetos que representan diferentes archivos en el disco, pero no hay forma de distinguirlos en JS en el navegador). En estos casos, desafortunadamente, todo lo que puede hacer es refactorizar su código para eliminar la necesidad de almacenarlos en un mayo; tal vez, utilizando una matriz en su lugar y referenciándolos exclusivamente por índice.

 20
Author: Rich,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-06-21 08:54:54
var map = {'myKey1':myObj1, 'mykey2':myObj2};
// You don't need any get function, just use
map['mykey1']
 14
Author: David,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-12-08 10:18:37

Si no está restringido a jQuery, puede usar el prototipo.js framework. Tiene una clase llamada Hash: Incluso puede usar jQuery & prototype.js juntos. Solo tienes que escribir jQuery.noConflict ();

var h = new Hash();
h.set("key", "value");
h.get("key");
h.keys(); // returns an array of keys
h.values(); // returns an array of values
 5
Author: polydor,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-03-07 13:22:58