Ronald Araújo Ronald Araújo - 2 months ago 7
Javascript Question

How get value in object JavaScript by number

Get the property value a javascript object is easy:

var t = {a:"hi"}
t.a //print "hi"


But for the next object, the same idea does not work:

var t = {0:"hi"}
t.0 //Uncaught SyntaxError: Unexpected number


How to get value of t.0?

Answer

Use t['0']. If a key can't be syntactically placed after the dot, you need to use this syntax.

Your first example could be similarly rewritten to t['hi'].

It's worth pointing out that the key is not a number at all. It's a string with the value '0'.

Comments