Home >Web Front-end >JS Tutorial >How to Create JavaScript Object Properties Using Variable Names?

How to Create JavaScript Object Properties Using Variable Names?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-08 16:42:10962browse

How to Create JavaScript Object Properties Using Variable Names?

Creating Object Properties from Variable Values in JavaScript

In JavaScript, adding properties to an object can be done in various ways. One common method is to use the dot notation, which allows you to create a property with the same name as the variable you specify. However, if you want to create a property with a name stored in a variable, you need to use a different approach.

To create an object property from a variable value, you can use the bracket notation. In this method, you enclose the property name in square brackets and assign the value of the variable to it. Here's an example:

var myObj = new Object();
var a = 'string1';
var b = 'string2';

myObj[a] = b;

alert(myObj.string1); //Returns 'undefined'
alert(myObj.a); //Returns 'string2'

As you can see, using the bracket notation, you can create a property with the name stored in the 'a' variable. The result of alert(myObj.string1) will be 'undefined' because the object doesn't have a property named 'string1'. However, alert(myObj.a) returns 'string2', which is what we assigned to the property using the 'a' variable.

The bracket notation is particularly useful when you want to dynamically create object properties based on user input or other dynamic data, providing greater flexibility in building JavaScript applications.

The above is the detailed content of How to Create JavaScript Object Properties Using Variable Names?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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