JavaScript Object: Accessing Variable Properties Using String Property Names
In JavaScript, it's possible to retrieve an object property's value using its name as a string. This approach is often useful when working with dynamic property names or when dealing with nested objects whose property names are not known at compile time.
To access an object property using its name as a string, you can use bracket notation:
var side = columns['right'];
This notation is equivalent to dot notation:
var side = columns.right;
However, bracket notation is more versatile, as it allows you to dynamically access properties based on variable values or function return values:
var propertyName = 'left'; var propertyValue = columns[propertyName];
If you prefer to use a function to access object properties by string name, here's a simple implementation:
function read_prop(obj, prop) { return obj[prop]; }
This function takes an object and a property name as arguments and returns the value of the corresponding property.
Nested Objects
When working with nested objects, you can access properties using multiple sets of brackets:
var foo = { a: 1, b: 2, c: { x: 999, y: 998, z: 997 } }; var cx = foo['c']['x'];
Undefined Properties
If an attempt is made to access an undefined property, the result will be undefined, not null or false:
foo['c']['q'] === null // returns false foo['c']['q'] === false // returns false foo['c']['q'] === undefined // returns true
The above is the detailed content of How Can I Access JavaScript Object Properties Using String Names?. For more information, please follow other related articles on the PHP Chinese website!