1

This is pretty basic...

I'm stuck on what to do though.

alert("The capital of " + n + " is " + capitals.n);

capitals.n in the alert comes out as undefined. What can I do to fix that?

  • possible duplicate of [javascript object, access variable property name?](http://stackoverflow.com/questions/4255472/javascript-object-access-variable-property-name) and [Dynamic object property name](http://stackoverflow.com/questions/4244896/dynamic-object-property-name). – Felix Kling Sep 27 '12 at 08:38

2 Answers2

2

Use square brackets:

alert("The capital of " + n + " is " + capitals[n]);

What you currently have will look for a property of capitals with the identifier n, which doesn't exist. Instead, you want to use the value of n as the identifier.

James Allardice
  • 164,175
  • 21
  • 332
  • 312
  • @FelixKling - Already have! I find it's usually more helpful to the OP to just answer first (seeing as it's such a quick and easy one) rather than finding a link to a dupe. – James Allardice Sep 27 '12 at 08:43
  • IMO it encourages to ask questions without searching first though. Ok, sometimes the OP does not know what to search for, but even then, it leaves the impression that simply asking is easier than searching, which should not be the case. It also generates noise (unnecessary amount of similar questions). I understand your point, I just find it unnecessary to duplicate content and I don't think it's good for the site in the long run. But that's not a discussion for comments... – Felix Kling Sep 27 '12 at 08:47
0

Use square brackets instead of dot notation:

alert("The capital of " + n + " is " + capitals[n]);

Explanation:

  • capitals.n looks for a property literally named 'n'.
  • capitals[n] looks for a property with the value of the variable n as a name.

(Verify by giving capitals.n a value in your code, like: capitals.n = 'FOO')

Leftium
  • 16,497
  • 6
  • 64
  • 99