最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Implementing a Map of String to Int in Javascript - Stack Overflow

programmeradmin1浏览0评论

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.

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.

Share Improve this question edited Jun 17, 2014 at 13:53 Cerbrus 73k19 gold badges136 silver badges150 bronze badges asked Jun 17, 2014 at 13:49 NixxusNixxus 991 gold badge1 silver badge7 bronze badges 2
  • 1 You can use Objects in JS, which is basically an equivalent of Java "map" string to Everything. – MarcoL Commented Jun 17, 2014 at 13:51
  • "Anything other than setting and receiving data" -- considering that's all a data structure does, what would "other" be? – Jon Commented Jun 17, 2014 at 13:52
Add a ment  | 

1 Answer 1

Reset to default 6

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}
发布评论

评论列表(0)

  1. 暂无评论