When working with JavaScript objects, it's often necessary to access properties by their names, which can be obtained dynamically or from user input. This question addresses how to write a function to retrieve a property value based on its name represented as a string.
The provided solution offers two approaches:
Bracket Notation:
This is the preferred method for accessing properties by name dynamically. It involves using brackets ([]), like:
var side = columns['right'];
Function (using bracket notation):
If you specifically require a function, you can use:
function read_prop(obj, prop) { return obj[prop]; }
If your object is nested, you can access property values using multiple brackets. For example, with the object:
var foo = { a: 1, b: 2, c: { x: 999, y: 998, z: 997 } };
you can access the property x like this:
var cx = foo['c']['x'];
If an attempted property reference results in an undefined property, it will return undefined (not null or false). For instance:
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 to Access JavaScript Object Properties Using a String for the Property Name?. For more information, please follow other related articles on the PHP Chinese website!