Ronald Araújo Ronald Araújo - 1 month ago 4x
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?


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