Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 417
Nixxus Avatar asked Aug 20 '26 06:08

Nixxus


1 Answers

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}
like image 117
Cerbrus Avatar answered Aug 22 '26 21:08

Cerbrus



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!