Domanda

Sto usando una tabella hash in JavaScript e voglio mostrare i valori seguenti in una tabella hash

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

Ho trovato il seguente codice. Funziona con i seguenti dati.

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

Come posso assegnare uno- [1,2] valori a una tabella hash e come accedervi?

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

Come posso farlo?

È stato utile?

Soluzione

Usando la funzione sopra, dovresti:

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

Ovviamente funzionerebbe anche quanto segue:

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

poiché tutti gli oggetti in JavaScript sono tabelle hash! Sarebbe, tuttavia, più difficile da ripetere poiché l'uso di foreach (var item in object) ti procurerebbe anche tutte le sue funzioni, ecc., Ma ciò potrebbe essere sufficiente a seconda delle tue esigenze.

Altri suggerimenti

Se tutto ciò che vuoi fare è memorizzare alcuni valori statici in una tabella di ricerca, puoi utilizzare un Object Literal (lo stesso formato utilizzato da JSON ) per farlo in modo compatto:

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

E quindi accedervi utilizzando la sintassi dell'array associativo di JavaScript:

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

Potresti usare l'implementazione della mia tabella hash JavaScript, jshashtable . Permette a qualsiasi oggetto di essere usato come chiave, non solo stringhe.

L'interprete Javascript memorizza nativamente gli oggetti in una tabella hash. Se sei preoccupato per la contaminazione dalla catena di prototipi, puoi sempre fare qualcosa del genere:

// 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
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top