Home >Web Front-end >JS Tutorial >How Can I Create Dynamic Object Properties in JavaScript Using Variable Names?
Creating Dynamic Object Properties with Variable Values in JavaScript
Despite the similarity in name, it's different to directly assign a property to an object using a variable value's name compared to assigning the variable's value. In the given case, accessing myObj.string1 returns 'undefined' because string1 is not a property of myObj.
To achieve the desired behavior, JavaScript provides two options:
Dot Notation:
myObj.a = b;
Using the dot notation, you can directly assign the property value using the variable name as the property key. However, this approach may not be suitable for dynamically created property names.
Bracket Notation:
myObj[a] = b;
Bracket notation offers greater flexibility. Here, the variable a holds the property name, and the value b is assigned to the property. This method is preferred for dynamically creating property names or when the property name contains special characters.
The above is the detailed content of How Can I Create Dynamic Object Properties in JavaScript Using Variable Names?. For more information, please follow other related articles on the PHP Chinese website!