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

How Can I Access JavaScript Object Properties Dynamically?

Barbara Streisand
Release: 2024-12-24 19:59:15
Original
591 people have browsed it

How Can I Access JavaScript Object Properties Dynamically?

Accessing JavaScript Object Properties Dynamically by Name

Consider an object with boolean properties:

var columns = {
  left: true,
  center: false,
  right: false
};
Copy after login

To retrieve a property value dynamically based on a provided string variable, such as "right," you can use either bracket or dot notation.

Bracket Notation:

var side = columns['right'];
Copy after login

This method allows referencing property names stored in variables or obtained dynamically.

Dot Notation:

var side = columns.right;
Copy after login

Dot notation is ideal when the property name is a known string constant.

Function for Dynamic Property Access

If a function is preferred:

function read_prop(obj, prop) {
  return obj[prop];
}
Copy after login

Nested Objects

Nested object properties can be accessed using multiple brackets or dot notation, e.g.:

var foo = { a: 1, b: 2, c: { x: 999, y: 998, z: 997 } };
var cx = foo['c']['x'];
Copy after login

Undefined Properties

If a property is undefined, referencing it will return undefined:

foo['c']['q'] === null; // false
foo['c']['q'] === false; // false
foo['c']['q'] === undefined; // true
Copy after login

The above is the detailed content of How Can I Access JavaScript Object Properties Dynamically?. 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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template