Home > Web Front-end > JS Tutorial > body text

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

WBOY
Release: 2023-08-24 18:37:02
forward
1170 people have browsed it

如何使用变量作为名称向 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)
Copy after login

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)
Copy after login

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!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!