Home > Web Front-end > JS Tutorial > How Can I Dynamically Add Properties to JavaScript Objects Using Variables?

How Can I Dynamically Add Properties to JavaScript Objects Using Variables?

Patricia Arquette
Release: 2024-12-10 18:00:30
Original
747 people have browsed it

How Can I Dynamically Add Properties to JavaScript Objects Using Variables?

Dynamically Creating Object Properties through Variables

When seeking to add new properties to an object in JavaScript, relying solely on the dot notation can prove limiting. Consider the need to assign a property name stored in a variable. In such situations, the answer lies in employing the bracket notation.

Imagine an object, aptly named myObj, that lacks the desired property string1. Utilizing the dot notation, you may attempt:

var myObj = new Object;
var a = 'string1';
var b = 'string2';
myObj.a = b;
Copy after login

Upon inspecting myObj, you'll notice the 'string1' property remains elusive, replaced by 'a'. This is where bracket notation shines:

myObj[a] = b;
Copy after login

This modification grants myObj the 'string1' property with the 'string2' value. The key to this success lies in treating the property name as a string within brackets, allowing for dynamic property creation.

The above is the detailed content of How Can I Dynamically Add Properties to JavaScript Objects Using Variables?. 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