3

Is this the right way to declare a static Javascript map of String keys and String values?

var myMap = {
    "key 1" : "value 1", 
    "key 2" : "value 2", 
    ...
    "key n" : "value n"
};

REM: all keys and values will be html escaped for special characters, they may contain blank spaces.

Jérôme Verstrynge
  • 57,710
  • 92
  • 283
  • 453
  • looks correct to me. Did you try it? – Alnitak Apr 11 '13 at 10:49
  • Yes. 11 more characters to go. – gmaliar Apr 11 '13 at 10:49
  • close duplicate of http://stackoverflow.com/questions/14711956/how-to-fill-a-javascript-map-with-many-static-key-value-pairs-efficiently?rq=1 – Alnitak Apr 11 '13 at 10:53
  • Sorry, the answer to this question is already available in another of my questions: http://stackoverflow.com/questions/14711956/how-to-fill-a-javascript-map-with-many-static-key-value-pairs-efficiently?rq=1. Still need to finish my morning coffee lol – Jérôme Verstrynge Apr 11 '13 at 10:57

2 Answers2

4

Yes, that's the normal and correct way to initialize a Javascript object.

Barmar
  • 741,623
  • 53
  • 500
  • 612
1

Is this the right way to declare a static Javascript map of String keys and String values?

That's a fine object literal, yes. Though, there is nothing really "static" in JavaScript (only the scope of the myMap variable which you declared with var, but not it's value).

all keys and values will be html escaped for special characters

That sounds unnecessary, unless you expect the strings to be written into html markup (and there are better ways). If you just escaped them since the script is included in a html document, it was useless - the only thing that needs to be escaped in inline scripts is the sequence </script>. You just have to string-escape them (i.e. escape backslashes and quotes).

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • How? If you properly use `document.createTextNode`, you don't need to escape them. Only if you do something like `"
    "+key+myMap[key]+"
    "` you need to worry about escaping (and injections).
    – Bergi Apr 11 '13 at 11:03