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!