myobj[map_id] means access to a property whose name is the value of map_id (as an expression).
In your case, the map_id value is 100. All properties of the object must be strings or valid JavaScript identifiers - therefore, it is converted to String '100' and placed as a property of the object.
In the case of var myobj2 = { map_id : 6 }; the JavaScript interpreter sees that map_id is a valid identifier and does not expect it to be an expression, so it does not transform into anything.
EDIT:
as in relation to your second question and assuming that you want the property name to be dynamic (as depending on the value of some expression), but also write:
var myobj2 = { map_id : 6 };
and replace map_id with "it" (this is not its value - two identifiers have the same name - one property of the object, and the other a variable) to create:
{ '100': 6 }
- the answer is no, you need to do this via
[] .
Zenmaster
source share