Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
160
rated 0 times [  164] [ 4]  / answers: 1 / hits: 19969  / 15 Years ago, fri, january 8, 2010, 12:00:00

I have an object like:



var myObject = { '0' : 'blue' };


Now, when I try to access the value of the key '0' like:



myObject.0 


...I am getting an error. (Maybe this is not the proper way?)



How can I access the value of a key that is a number (like the above)?


More From » javascript

 Answers
18

This should work:



myObject[0]


(myObject[propertyName] is an alternative syntax for myObject.propertyName.)



You're getting the error because, in JavaScript, identifiers can't begin with a numeral. From the Variables page at the Mozilla Developer Centre:




A JavaScript identifier must start
with a letter, underscore (_), or
dollar sign ($); subsequent characters
can also be digits (0-9). Because
JavaScript is case sensitive, letters
include the characters A through Z
(uppercase) and the characters a
through z (lowercase).



[#97889] Tuesday, January 5, 2010, 15 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
parker

Total Points: 259
Total Questions: 109
Total Answers: 97

Location: Zambia
Member since Thu, Jun 25, 2020
4 Years ago
;