Pergunta

Eu estou usando uma tabela hash em JavaScript, e eu quero mostrar os valores do seguinte em uma tabela hash

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

Eu encontrei o código a seguir. Ele funciona para os seguintes dados.

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

Como atribuir um- [1,2] valores para uma tabela hash e como posso acessá-lo?

<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>

Como posso fazê-lo?

Foi útil?

Solução

Usando a função acima, você faria:

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

É claro, o seguinte seria também trabalho:

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

desde todos os objetos em JavaScript são tabelas de hash! Seria, no entanto, ser mais difícil para repetir uma vez usando foreach(var item in object) também que você obtenha todas as suas funções, etc., mas isso pode ser suficiente, dependendo de suas necessidades.

Outras dicas

Se tudo que você quer fazer é armazenar alguns valores estáticos em uma tabela de pesquisa, você pode usar um objeto Literal (o mesmo formato utilizado pelo JSON ) para fazê-lo de forma compacta:

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

E então acessá-los usando a sintaxe de matriz associativa de JavaScript:

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

Você pode usar minha implementação de tabela de hash JavaScript, jshashtable . Ele permite que qualquer objeto a ser usado como uma chave, não apenas strings.

A Javascript intérprete lojas nativamente objetos em uma tabela hash. Se você está preocupado com a contaminação da cadeia de protótipos, você sempre pode fazer algo como isto:

// 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 em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top