0

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?

1 Answer 1

6

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

Sign up to request clarification or add additional context in comments.

8 Comments

"If a key can't be syntactically placed after the dot" --- +1'd, but it would be even more helpful if the rules or at least a tiny excerpt of those was provided on what is syntactically valid to be used there and what is not.
@zerkms "If the key cannot be used a valid variable identifier (var not-valid; for example) then it must be accessed via the square bracket syntax"? I'm curious how you would provide the rules?
@zerkms It's invalid syntax when using dots for a variable to start with a number, it includes properties as well.
@SpencerWieczorek well, I can check the standard with no problem, my suggestion addressed the answer improvement
The expression inside the square brackets need not be a string, t[0] is also valid. What's important to notice is that square brackets take an expression, while the dot syntax expects a valid identifier
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.