Home  >  Article  >  Web Front-end  >  How to add a property to a JavaScript object using a variable as name?

How to add a property to a JavaScript object using a variable as name?

WBOY
WBOYforward
2023-08-24 18:37:021187browse

如何使用变量作为名称向 JavaScript 对象添加属性?

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 ([]).

Example 1

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)

illustrate

  • Step 1 - Define an object, inputObject.

  • Step 2 - Use dot notation to add additional properties to the object.

  • Step 3 - Display the value.

Example 2

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)

illustrate

  • 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!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete