Nixxus
Nixxus

Reputation: 99

Implementing a Map of String to Int in Javascript

I'm looking to use a map to map a string to an integer value but allowing the int to be manipulated within the map.

E.g.

var Map : map<string, int>;

Map["foo"] = 5;
Map["foo"] = Map["foo"] * 5;
Map["bar"] = 10;
Map["baz"] = Map["foo"] + Map["bar"];

I've seen other questions using objects for the purpose, but this seems to result in errors when mapping anything other than strings to strings, or doing anything other than setting and receiving data.

Upvotes: 3

Views: 14264

Answers (1)

Cerbrus
Cerbrus

Reputation: 72947

This:

var Map : map<string, int>;

Ain't valid JavaScript syntax. JavaScript isn't strongly typed.

You probably just want to use a object:

var Map = {};

Then you can perform the calculations you posted in your question just fine:

Map["foo"] = 5;
Map["foo"] = Map["foo"] * 5;
Map["bar"] = 10;
Map["baz"] = Map["foo"] + Map["bar"];

console.log(Map);
// Object {foo: 25, bar: 10, baz: 35}

Upvotes: 6

Related Questions