In this article, you will learn how to add properties to JavaScript objects using variables as names. Adding properties to an object can be accomplished in two ways. The first is dot (.) notation and the second is using square brackets ([]).
In this example, we use dot (.) notation.
var inputObject = {a: "value1"}; console.log("An object is created with properties: ", inputObject) inputObject.b = "value2"; console.log("After adding properties, the object now contains: ", inputObject) console.log(inputObject)
Step 1 - Define an object, inputObject.
Step 2 - Use dot notation to add additional properties to the object.
Step 3 - Display the value.
In this example,
var inputObject = {a: "value1"}; console.log("An object is created with properties: ", inputObject) inputObject['c'] = "value3" console.log("After adding properties, the object now contains: ", inputObject) console.log(inputObject)
Step 1 - Define an object, inputObject.
Step 2 - Add additional properties to the object using bracket notation.
Step 3 - Display the value.
The above is the detailed content of How to add a property to a JavaScript object using a variable as name?. For more information, please follow other related articles on the PHP Chinese website!