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
Patricia ArquetteOriginal
2024-12-10 18:00:30741browse

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;

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

myObj[a] = b;

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!

Statement:
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