Pregunta

Estoy usando una tabla hash en JavaScript, y quiero mostrar los valores de lo siguiente en una tabla hash

one   -[1,10,5]
two   -[2]
three -[3, 30, 300, etc.]

He encontrado el siguiente código. Funciona para los siguientes datos.

   one  -[1]
   two  -[2]
   three-[3]

¿Cómo asigno uno- [1,2] valores a una tabla hash y cómo accedo a ella?

<script type="text/javascript">
    function Hash()
    {
        this.length = 0;
        this.items = new Array();
        for (var i = 0; i < arguments.length; i += 2) {
            if (typeof(arguments[i + 1]) != 'undefined') {
                this.items[arguments[i]] = arguments[i + 1];
                this.length++;
            }
        }

        this.removeItem = function(in_key)
        {
            var tmp_value;
            if (typeof(this.items[in_key]) != 'undefined') {
                this.length--;
                var tmp_value = this.items[in_key];
                delete this.items[in_key];
            }
            return tmp_value;
        }

        this.getItem = function(in_key) {
            return this.items[in_key];
        }

        this.setItem = function(in_key, in_value)
        {
            if (typeof(in_value) != 'undefined') {
                if (typeof(this.items[in_key]) == 'undefined') {
                    this.length++;
                }

                this.items[in_key] = in_value;
            }
            return in_value;
        }

        this.hasItem = function(in_key)
        {
            return typeof(this.items[in_key]) != 'undefined';
        }
    }

    var myHash = new Hash('one',1,'two', 2, 'three',3 );

    for (var i in myHash.items) {
        alert('key is: ' + i + ', value is: ' + myHash.items[i]);
    }
</script>

¿Cómo lo hago?

¿Fue útil?

Solución

Usando la función anterior, haría:

var myHash = new Hash('one',[1,10,5],'two', [2], 'three',[3,30,300]);

Por supuesto, lo siguiente también funcionaría:

var myHash = {}; // New object
myHash['one'] = [1,10,5];
myHash['two'] = [2];
myHash['three'] = [3, 30, 300];

¡ya que todos los objetos en JavaScript son tablas hash! Sin embargo, sería más difícil iterar ya que usar foreach (elemento var en objeto) también le proporcionaría todas sus funciones, etc., pero eso podría ser suficiente dependiendo de sus necesidades.

Otros consejos

Si todo lo que quiere hacer es almacenar algunos valores estáticos en una tabla de búsqueda, puede usar un Object Literal (el mismo formato utilizado por JSON ) para hacerlo de forma compacta:

var table = { one: [1,10,5], two: [2], three: [3, 30, 300] }

Y luego acceda a ellos utilizando la sintaxis de matriz asociativa de JavaScript:

alert(table['one']);    // Will alert with [1,10,5]
alert(table['one'][1]); // Will alert with 10

Puede usar la implementación de mi tabla hash de JavaScript, jshashtable . Permite que cualquier objeto se use como clave, no solo cadenas.

El intérprete de Javascript almacena objetos de forma nativa en una tabla hash. Si le preocupa la contaminación de la cadena de prototipos, siempre puede hacer algo como esto:

// Simple ECMA5 hash table
Hash = function(oSource){
  for(sKey in oSource) if(Object.prototype.hasOwnProperty.call(oSource, sKey)) this[sKey] = oSource[sKey];
};
Hash.prototype = Object.create(null);

var oHash = new Hash({foo: 'bar'});
oHash.foo === 'bar'; // true
oHash['foo'] === 'bar'; // true
oHash['meow'] = 'another prop'; // true
oHash.hasOwnProperty === undefined; // true
Object.keys(oHash); // ['foo', 'meow']
oHash instanceof Hash; // true
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top