views:

348

answers:

2

What's the best way to store a key=>value array in javascript, and how can that be looped through?

The key of each element should be a tag, such as {id} or just id and the value should be the numerical value of the id.

It should either be the element of an existing javascript class, or be a global variable which could easily be referenced through the class.

Jquery can be used

+7  A: 

If I understood you correctly:

var hash = {};
hash['bob'] = 123;
hash['joe'] = 456;

var sum = 0;
for (var name in hash) {
    sum += hash[name];
}
alert(sum); // 579
Blixt
Exactly. No reason for jQuery here.
Artem Russakovskii
+6  A: 

That's just what a Javascript object is:

var MyArray = {id1: 100, id2: 200, "tag with spaces": 300};
MyArray.id3 = 400;
MyArray["id4"] = 500;

for(key in myArray)
{
  alert("key " + key
    + " has value "
    + myArray[key]);
}
Alexey Romanov