I am a newbie to JavaScript, but I am familiar with Python. I am trying to figure out the differences between the Dictionary in Python and the Object in JS.
As far as I know, the key in a dictionary in Python needs to be defined in advance, but it could be undefined in an object in JS. However, I am confused about those cases:
var n = 'name';
var n2 = n;
var person = {n: 'mike'};
person.n # 'mike'
person['n'] # 'mike'
person[n2] # undefined
person.n2 # undefined
person['name'] # undefined
person.'name' # undefined
I am so confused that why those three variables n
, n2
and name
are not equal, because compared with that in Python:
n = 'name'
n2 = n
person = {n:'mike'}
person[n] # 'mike'
person[n2] # 'mike'
person['name'] # 'mike'
I guess that might due to the fact that in Python, n
and n2
both point to the unique string object 'name'
, so they are the same. But could someone explain the mechanism behind in JS to me?
When you assign like:
var person = {n: 'mike'};
The n is not referencing to the variable but it's own property. If you need to reference the variable you will need to use bracket notation like:
var person = {[n]: 'mike'};
For more information about bracket notation, see computed property.
In JavaScript, the use of quote for property is same without using quote:
var person = {n: 'mike'};
var person = {'n': 'mike'}; // same as above
But if you define property like giving space:
var person = {my property: 'mike'}; // invalid
In this case, you must need to use the quote:
var person = {'my property': 'mike'};
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