farjam farjam - 2 months ago 6
Javascript Question

Cannot read properties of a JavsScript function

I have a php array that I'm

json_encode
ing into a JavaScript object. When I preview the object in console, it looks something like this:

Object { 1="some text", 2="something else", 3="extra text"}


Shouldn't I be able to read the value for index 1 like this (pretending my object name is obj)?

obj.1


Doing that gives me the
undefined
error message. How would access the value for the exact index of 1?

Answer

You can only access a property using dot notation if the property name is a valid identifier. Identifiers cannot start with a number.

You have to use square bracket notation for other properties.

obj[1]
Comments