Ronald Araújo
Ronald Araújo

Reputation: 1479

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?

Upvotes: 0

Views: 46

Answers (1)

user94559
user94559

Reputation: 60143

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

Upvotes: 6

Related Questions