Home > Web Front-end > JS Tutorial > How Can I Access JavaScript Object Properties Using String Names?

How Can I Access JavaScript Object Properties Using String Names?

DDD
Release: 2024-12-17 06:49:25
Original
798 people have browsed it

How Can I Access JavaScript Object Properties Using String Names?

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'];
Copy after login

This notation is equivalent to dot notation:

var side = columns.right;
Copy after login

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];
Copy after login

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];
}
Copy after login

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'];
Copy after login

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
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template