Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access a numeric property?

Tags:

javascript

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)?

like image 204
Prashant Avatar asked Jan 08 '10 09:01

Prashant


People also ask

How do you access the properties of objects in typescript?

To dynamically access an object's property: Use keyof typeof obj as the type of the dynamic key, e.g. type ObjectKey = keyof typeof obj; . Use bracket notation to access the object's property, e.g. obj[myVar] .

Can an object property be a number?

According to the official JavaScript documentation you can define object literal property names using integers: Additionally, you can use a numeric or string literal for the name of a property.


2 Answers

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).

like image 185
Steve Harrison Avatar answered Oct 07 '22 22:10

Steve Harrison


myObject["0"]

like image 33
Amarghosh Avatar answered Oct 07 '22 22:10

Amarghosh