Domanda

Devo memorizzare alcune statistiche usando JavaScript in un modo come farei in C #:

Dictionary<string, int> statistics;

statistics["Foo"] = 10;
statistics["Goo"] = statistics["Goo"] + 1;
statistics.Add("Zoo", 1);

C'è un Hashtable o qualcosa di simile a Dictionary<TKey, TValue> in JavaScript?
Come potrei archiviare i valori in questo modo?

È stato utile?

Soluzione

Usa oggetti JavaScript come array associativi .

  

Matrice associativa: in parole semplici, le matrici associative usano le stringhe anziché i numeri interi come indice.

Crea un oggetto con

var dictionary = {};
  

Javascript consente di aggiungere proprietà agli oggetti utilizzando la sintassi seguente:

Object.yourProperty = value;

Una sintassi alternativa per lo stesso è:

Object["yourProperty"] = value;

Se puoi anche creare la chiave per valutare le mappe di oggetti con la seguente sintassi

var point = { x:3, y:2 };

point["x"] // returns 3
point.y // returns 2
  

Puoi iterare attraverso un array associativo usando il costrutto del ciclo for..in come segue

for(var key in Object.keys(dict)){
  var value = dict[key];
  /* use key/value for intended purpose */
}

Altri suggerimenti

var associativeArray = {};
associativeArray["one"] = "First";
associativeArray["two"] = "Second";
associativeArray["three"] = "Third";

Se provieni da un linguaggio orientato agli oggetti, controlla questo articolo .

A meno che tu non abbia un motivo specifico per non farlo, usa semplicemente un oggetto normale. È possibile fare riferimento alle proprietà degli oggetti in Javascript utilizzando la sintassi in stile hashtable:

var hashtable = {};
hashtable.foo = "bar";
hashtable['bar'] = "foo";

Entrambi gli elementi foo e bar possono ora essere indicati come:

hashtable['foo'];
hashtable['bar'];
// or
hashtable.foo;
hashtable.bar;

Ovviamente questo significa che le tue chiavi devono essere stringhe. Se non sono stringhe, vengono convertite internamente in stringhe, quindi potrebbe funzionare ancora, YMMV.

Tutti i browser moderni supportano un oggetto javascript Map . Ci sono un paio di ragioni che rendono l'utilizzo di una mappa migliore di Object:

  
      
  • Un oggetto ha un prototipo, quindi ci sono chiavi predefinite nella mappa.
  •   
  • Le chiavi di un oggetto sono stringhe, dove possono avere qualsiasi valore per una mappa.
  •   
  • Puoi ottenere facilmente le dimensioni di una Mappa mentre devi tenere traccia delle dimensioni di un Oggetto.
  •   

Esempio:

var myMap = new Map();

var keyObj = {},
    keyFunc = function () {},
    keyString = "a string";

myMap.set(keyString, "value associated with 'a string'");
myMap.set(keyObj, "value associated with keyObj");
myMap.set(keyFunc, "value associated with keyFunc");

myMap.size; // 3

myMap.get(keyString);    // "value associated with 'a string'"
myMap.get(keyObj);       // "value associated with keyObj"
myMap.get(keyFunc);      // "value associated with keyFunc"

Se desideri che le chiavi a cui non viene fatto riferimento da altri oggetti vengano raccolte in modo inutile, prendi in considerazione l'utilizzo di WeakMap anziché una mappa.

Poiché ogni oggetto in JS si comporta come - ed è generalmente implementato come - una tabella hash, vado semplicemente con quello ...

var hashSweetHashTable = {};

quindi in C # il codice è simile a:

Dictionary<string,int> dictionary = new Dictionary<string,int>();
dictionary.add("sample1", 1);
dictionary.add("sample2", 2);

o

var dictionary = new Dictionary<string, int> {
    {"sample1", 1},
    {"sample2", 2}
};

in JavaScript

var dictionary = {
    "sample1": 1,
    "sample2": 2
}

L'oggetto dizionario C # contiene metodi utili come dictionary.ContainsKey() in JavaScript potremmo usare il hasOwnProperty come

if (dictionary.hasOwnProperty("sample1"))
    console.log("sample1 key found and its value is"+ dictionary["sample1"]);

Se richiedi che le tue chiavi siano qualsiasi oggetto anziché solo stringhe, puoi usare il mio jshashtable .

L'ho creato per risolvere alcuni problemi, come la mappatura delle chiavi degli oggetti, la capacità di enumerazione (con il metodo forEach()) e la cancellazione.

function Hashtable() {
    this._map = new Map();
    this._indexes = new Map();
    this._keys = [];
    this._values = [];
    this.put = function(key, value) {
        var newKey = !this.containsKey(key);
        this._map.set(key, value);
        if (newKey) {
            this._indexes.set(key, this.length);
            this._keys.push(key);
            this._values.push(value);
        }
    };
    this.remove = function(key) {
        if (!this.containsKey(key))
            return;
        this._map.delete(key);
        var index = this._indexes.get(key);
        this._indexes.delete(key);
        this._keys.splice(index, 1);
        this._values.splice(index, 1);
    };
    this.indexOfKey = function(key) {
        return this._indexes.get(key);
    };
    this.indexOfValue = function(value) {
        return this._values.indexOf(value) != -1;
    };
    this.get = function(key) {
        return this._map.get(key);
    };
    this.entryAt = function(index) {
        var item = {};
        Object.defineProperty(item, "key", {
            value: this.keys[index],
            writable: false
        });
        Object.defineProperty(item, "value", {
            value: this.values[index],
            writable: false
        });
        return item;
    };
    this.clear = function() {
        var length = this.length;
        for (var i = 0; i < length; i++) {
            var key = this.keys[i];
            this._map.delete(key);
            this._indexes.delete(key);
        }
        this._keys.splice(0, length);
    };
    this.containsKey = function(key) {
        return this._map.has(key);
    };
    this.containsValue = function(value) {
        return this._values.indexOf(value) != -1;
    };
    this.forEach = function(iterator) {
        for (var i = 0; i < this.length; i++)
            iterator(this.keys[i], this.values[i], i);
    };
    Object.defineProperty(this, "length", {
        get: function() {
            return this._keys.length;
        }
    });
    Object.defineProperty(this, "keys", {
        get: function() {
            return this._keys;
        }
    });
    Object.defineProperty(this, "values", {
        get: function() {
            return this._values;
        }
    });
    Object.defineProperty(this, "entries", {
        get: function() {
            var entries = new Array(this.length);
            for (var i = 0; i < entries.length; i++)
                entries[i] = this.entryAt(i);
            return entries;
        }
    });
}

Documentazione della classe Hashtable

Metodi:

  • get(key)
    Restituisce il valore associato alla chiave specificata.
    Parametri:
    key: la chiave da cui recuperare il valore.

  • put(key, value)
    Associa il valore specificato alla chiave specificata.
    Parametri:
    value: la chiave a cui associare il valore.
    remove(key): il valore da associare alla chiave.

  • clear()
    Rimuove la chiave specificata con il suo valore.
    Parametri:
    indexOfKey(key): la chiave da rimuovere.

  • indexOfValue(value)
    Cancella tutta la tabella hash, rimuovendo sia le chiavi che i valori.

  • indexOf()
    Restituisce l'indice della chiave specificata, in base all'ordine di aggiunta.
    Parametri:
    toString(): la chiave per ottenere l'indice.

  • entryAt(index)
    Restituisce l'indice del valore specificato, in base all'ordine di aggiunta.
    Parametri:
    index: il valore di cui ottiene l'indice.
    Note:
    Queste informazioni vengono recuperate dal containsKey(key) metodo di un array, quindi confronta l'oggetto solo con il metodo containsValue(value).

  • forEach(iterator)
    Restituisce un oggetto con due proprietà: chiave e valore, che rappresentano la voce nell'indice specificato.
    Parametri:
    iterator: l'indice della voce da ottenere.

  • length
    Indica se l'hashtable contiene la chiave specificata.
    Parametri:
    keys: la chiave da controllare.

  • values
    Indica se l'hashtable contiene il valore specificato.
    Parametri:
    entries: il valore da verificare.

  • entryAt()
    Scorre tutte le voci nel <=>.
    Parametri specificato:
    <=>: un metodo con 3 parametri: <=>, <=> e <=>, dove <=> rappresenta l'indice della voce.

    Proprietà:

  • &
  • <=> # 8195; ( di sola lettura )
    Ottiene il conteggio delle voci nella tabella hash.

  • &
  • <=> # 8195; ( di sola lettura )
    Ottiene una matrice di tutte le chiavi nella tabella hash.

  • &
  • <=> # 8195; ( di sola lettura )
    Ottiene una matrice di tutti i valori nella tabella hash.

  • &
  • <=> # 8195; ( di sola lettura )
    Ottiene una matrice di tutte le voci nella tabella hash. Sono rappresentati nella stessa forma del metodo <=>.

function HashTable() {
    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_previous;
        if (typeof (this.items[in_key]) != 'undefined') {
            this.length--;
            var tmp_previous = this.items[in_key];
            delete this.items[in_key];
        }

        return tmp_previous;
    }

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

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

            this.items[in_key] = in_value;
        }

        return tmp_previous;
    }

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

    this.clear = function () {
        for (var i in this.items) {
            delete this.items[i];
        }

        this.length = 0;
    }
}

https://gist.github.com/alexhawkins/f6329420f40e5cafa0a4

var HashTable = function() {
  this._storage = [];
  this._count = 0;
  this._limit = 8;
}


HashTable.prototype.insert = function(key, value) {
  //create an index for our storage location by passing it through our hashing function
  var index = this.hashFunc(key, this._limit);
  //retrieve the bucket at this particular index in our storage, if one exists
  //[[ [k,v], [k,v], [k,v] ] , [ [k,v], [k,v] ]  [ [k,v] ] ]
  var bucket = this._storage[index]
    //does a bucket exist or do we get undefined when trying to retrieve said index?
  if (!bucket) {
    //create the bucket
    var bucket = [];
    //insert the bucket into our hashTable
    this._storage[index] = bucket;
  }

  var override = false;
  //now iterate through our bucket to see if there are any conflicting
  //key value pairs within our bucket. If there are any, override them.
  for (var i = 0; i < bucket.length; i++) {
    var tuple = bucket[i];
    if (tuple[0] === key) {
      //overide value stored at this key
      tuple[1] = value;
      override = true;
    }
  }

  if (!override) {
    //create a new tuple in our bucket
    //note that this could either be the new empty bucket we created above
    //or a bucket with other tupules with keys that are different than 
    //the key of the tuple we are inserting. These tupules are in the same
    //bucket because their keys all equate to the same numeric index when
    //passing through our hash function.
    bucket.push([key, value]);
    this._count++
      //now that we've added our new key/val pair to our storage
      //let's check to see if we need to resize our storage
      if (this._count > this._limit * 0.75) {
        this.resize(this._limit * 2);
      }
  }
  return this;
};


HashTable.prototype.remove = function(key) {
  var index = this.hashFunc(key, this._limit);
  var bucket = this._storage[index];
  if (!bucket) {
    return null;
  }
  //iterate over the bucket
  for (var i = 0; i < bucket.length; i++) {
    var tuple = bucket[i];
    //check to see if key is inside bucket
    if (tuple[0] === key) {
      //if it is, get rid of this tuple
      bucket.splice(i, 1);
      this._count--;
      if (this._count < this._limit * 0.25) {
        this._resize(this._limit / 2);
      }
      return tuple[1];
    }
  }
};



HashTable.prototype.retrieve = function(key) {
  var index = this.hashFunc(key, this._limit);
  var bucket = this._storage[index];

  if (!bucket) {
    return null;
  }

  for (var i = 0; i < bucket.length; i++) {
    var tuple = bucket[i];
    if (tuple[0] === key) {
      return tuple[1];
    }
  }

  return null;
};


HashTable.prototype.hashFunc = function(str, max) {
  var hash = 0;
  for (var i = 0; i < str.length; i++) {
    var letter = str[i];
    hash = (hash << 5) + letter.charCodeAt(0);
    hash = (hash & hash) % max;
  }
  return hash;
};


HashTable.prototype.resize = function(newLimit) {
  var oldStorage = this._storage;

  this._limit = newLimit;
  this._count = 0;
  this._storage = [];

  oldStorage.forEach(function(bucket) {
    if (!bucket) {
      return;
    }
    for (var i = 0; i < bucket.length; i++) {
      var tuple = bucket[i];
      this.insert(tuple[0], tuple[1]);
    }
  }.bind(this));
};


HashTable.prototype.retrieveAll = function() {
  console.log(this._storage);
  //console.log(this._limit);
};

/******************************TESTS*******************************/

var hashT = new HashTable();

hashT.insert('Alex Hawkins', '510-599-1930');
//hashT.retrieve();
//[ , , , [ [ 'Alex Hawkins', '510-599-1930' ] ] ]
hashT.insert('Boo Radley', '520-589-1970');
//hashT.retrieve();
//[ , [ [ 'Boo Radley', '520-589-1970' ] ], , [ [ 'Alex Hawkins', '510-599-1930' ] ] ]
hashT.insert('Vance Carter', '120-589-1970').insert('Rick Mires', '520-589-1970').insert('Tom Bradey', '520-589-1970').insert('Biff Tanin', '520-589-1970');
//hashT.retrieveAll();
/* 
[ ,
  [ [ 'Boo Radley', '520-589-1970' ],
    [ 'Tom Bradey', '520-589-1970' ] ],
  ,
  [ [ 'Alex Hawkins', '510-599-1930' ],
    [ 'Rick Mires', '520-589-1970' ] ],
  ,
  ,
  [ [ 'Biff Tanin', '520-589-1970' ] ] ]
*/

//overide example (Phone Number Change)
//
hashT.insert('Rick Mires', '650-589-1970').insert('Tom Bradey', '818-589-1970').insert('Biff Tanin', '987-589-1970');
//hashT.retrieveAll();

/* 
[ ,
  [ [ 'Boo Radley', '520-589-1970' ],
    [ 'Tom Bradey', '818-589-1970' ] ],
  ,
  [ [ 'Alex Hawkins', '510-599-1930' ],
    [ 'Rick Mires', '650-589-1970' ] ],
  ,
  ,
  [ [ 'Biff Tanin', '987-589-1970' ] ] ]

*/

hashT.remove('Rick Mires');
hashT.remove('Tom Bradey');
//hashT.retrieveAll();

/* 
[ ,
  [ [ 'Boo Radley', '520-589-1970' ] ],
  ,
  [ [ 'Alex Hawkins', '510-599-1930' ] ],
  ,
  ,
  [ [ 'Biff Tanin', '987-589-1970' ] ] ]


*/

hashT.insert('Dick Mires', '650-589-1970').insert('Lam James', '818-589-1970').insert('Ricky Ticky Tavi', '987-589-1970');
hashT.retrieveAll();


/* NOTICE HOW HASH TABLE HAS NOW DOUBLED IN SIZE UPON REACHING 75% CAPACITY ie 6/8. It is now size 16.
 [,
  ,
  [ [ 'Vance Carter', '120-589-1970' ] ],
  [ [ 'Alex Hawkins', '510-599-1930' ],
    [ 'Dick Mires', '650-589-1970' ],
    [ 'Lam James', '818-589-1970' ] ],
  ,
  ,
  ,
  ,
  ,
  [ [ 'Boo Radley', '520-589-1970' ],
    [ 'Ricky Ticky Tavi', '987-589-1970' ] ],
  ,
  ,
  ,
  ,
  [ [ 'Biff Tanin', '987-589-1970' ] ] ]




*/
console.log(hashT.retrieve('Lam James'));  //818-589-1970
console.log(hashT.retrieve('Dick Mires')); //650-589-1970
console.log(hashT.retrieve('Ricky Ticky Tavi')); //987-589-1970
console.log(hashT.retrieve('Alex Hawkins')); //510-599-1930
console.log(hashT.retrieve('Lebron James')); //null

Puoi crearne uno usando il seguente:

var dictionary = { Name:"Some Programmer", Age:24, Job:"Writing Programs"  };

//Iterate Over using keys
for (var key in dictionary) {
  console.log("Key: " + key + " , " + "Value: "+ dictionary[key]);
}

//access a key using object notation:
console.log("Her Name is: " + dictionary.Name)

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top