In JavaScript, if you have the following code:
var map_id = 100;
var myobj = {};
myobj[map_id] = 6;
var myobj2 = { map_id : 6 };
console.log(myobj, myobj2);
The console output is as follows:
{ '100': 6 } { map_id: 6 }
Questions:
- Why does JavaScript syntax work differently in these two different cases – why is they key in
myobj2set to the literalmap_idrather than100? What is the reasoning behind having this difference? - Is there any way to set the key to the value of the
map_idvariable in a compact, one-line way, rather than having to define the object separately first?
Thanks.
No. Sorry.
(Unless you count putting both statements on one line separated by a semicolon, which I don’t.)
Good question. I don’t know, and I’ve never been able to think of a good reason. I think it would make much, much more sense if the key names were treated like expressions the same as pretty much everything else in JavaScript, i.e., as a literal if quoted (
{ "map_id" : 6 }), and as a variable if not quoted ({map_id : 6 }).