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:
myobj2
set to the literal map_id
rather than 100
? What is the reasoning behind having this difference?map_id
variable in a compact, one-line way, rather than having to define the object separately first?Thanks.
No, JavaScript objects cannot have duplicate keys. The keys must all be unique.
Against what many think, JavaScript object keys cannot be Number, Boolean, Null, or Undefined type values. Object keys can only be strings, and even though a developer can use other data types to set an object key, JavaScript automatically converts keys to a string a value.
Is there any way to set the key to the value of the map_id variable in a compact, one-line way, rather than having to define the object separately first?
No. Sorry.
(Unless you count putting both statements on one line separated by a semicolon, which I don't.)
Why does JavaScript syntax work differently in these two different cases - why is they key in myobj2 set to the literal map_id rather than 100? What is the reasoning behind having this difference?
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 }
).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With