I need to store some statistics using JavaScript in a way like I'd do it in C#:
Dictionary<string, int> statistics;
statistics["Foo"] = 10;
statistics["Goo"] = statistics["Goo"] + 1;
statistics.Add("Zoo", 1);
Is there an Hashtable
or something like Dictionary<TKey, TValue>
in JavaScript?
How could I store values in such a way?
Unless you have a specific reason not to, just use a normal object. Object properties in Javascript can be referenced using hashtable-style syntax:
Both
foo
andbar
elements can now then be referenced as:Of course this does mean your keys have to be strings. If they're not strings they are converted internally to strings, so it may still work, YMMV.
If you require your keys to be be any object rather than just strings then you could use my jshashtable.
Since every object in JS behaves like - and is generally implemented as - a hashtable, i just go with that...
If you are coming from an object-oriented language you should check this article.
so in C# the code looks like:
or
in JavaScript
C# dictionary object contains useful methods like
dictionary.ContainsKey()
in JavaScript we could use thehasOwnProperty
likeAll modern browsers support a javascript Map object. There are a couple of reasons that make using a Map better than Object:
Example:
If you want keys that are not referenced from other objects to be garbage collected, consider using a WeakMap instead of a Map.