How to do associative array/hashing in JavaScript

I want to calculate/store some statistics information using JavaScript, the equivalent code in C# is below (features I need are -- key-value pair, string/int key value pair, manipulate values by keys, etc.), any ideas how to implement the same function in JavaScript? Looks like there is no built-in Dictionary or Hashtable?

Dictionary<string, int> statistics;

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

Use JavaScript objects as associative arrays.

Associative Array: In simple words associative arrays use Strings instead of Integer numbers as index.

Create an object with

var dictionary = {};

Javascript allows you to add properties to objects by using the following syntax:

Object.yourProperty = value;

An alternate syntax for the same is:

Object["yourProperty"] = value;

If you can also create key to value object maps with the following syntax

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

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

You can iterate through an associative array using the for..in loop construct as follows

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

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

如果您来自面向对象的语言,您应该阅读本文。


Unless you have a specific reason not to, just use a normal object. Object properties in Javascript can be referenced using hashtable-style syntax:

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

Both foo and bar elements can now then be referenced as:

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

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.

链接地址: http://www.djcxy.com/p/91912.html

上一篇: Java中的HashMap和Map对象有什么区别?

下一篇: 如何在JavaScript中执行关联数组/散列