You can use the following syntax to do what you describe using bracket notation:
myObject["myProperty"]
Bracket notation differs from dot notation (e.g. myObject.myProperty
) in that it can be used to access properties whose names are illegal. Illegal meaning that with dot notation, you're limited to using property names that are alphanumeric (plus the underscore _
and dollar sign $
), and don't begin with a number. Bracket notation allows us to use a string to access a property and bypass this.
myObject.1 // fails, properties cannot begin with numbers
myObject.& // fails, properties must be alphanumeric (or $ or _)
myObject["1"] // succeeds
myObject["&"] // succeeds
This also means we can use string variables to look up and set properties on objects:
var myEdgyPropertyName = "||~~(_o__o_)~~||";
myEdgyObject[myEdgyPropertyName] = "who's there?";
myEdgyObject[myEdgyPropertyName] // "who's there?";
You can read more about dot and bracket notation here, on MDN.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…