Creating Object Properties from Variable Values in JavaScript
You may encounter situations where you need to dynamically create and assign values to object properties based on variable values. While the dot notation (e.g., myObj.property) is a convenient way to access existing properties, it may not always be suitable for creating new ones.
To dynamically create an object property from a variable value, you can utilize the bracket notation:
var myObj = new Object(); var a = 'string1'; var b = 'string2'; myObj[a] = b; alert(myObj[a]); //Returns 'string2'
In this example, the myObj[a] syntax allows us to create a new property named 'string1' with the value 'string2'. The variable 'a' stores the name of the property we want to create, while 'b' holds the value to assign.
The bracket notation is especially useful when you need to create properties with dynamic or user-defined names. It provides a versatile way to manipulate object properties at runtime.
The above is the detailed content of How Can I Create JavaScript Object Properties Dynamically Using Variable Values?. For more information, please follow other related articles on the PHP Chinese website!