Home  >  Article  >  Web Front-end  >  How Can I Use Variables as Property Names in JavaScript Objects?

How Can I Use Variables as Property Names in JavaScript Objects?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-02 03:26:02268browse

How Can I Use Variables as Property Names in JavaScript Objects?

Accessing Object Properties with Variables

Can JavaScript objects incorporate variables as property names, such as:

<code class="javascript">var myVar = "name";
var myObject = {
    {myVar}: "value"
};</code>

Solution: Computed Property Names

In ES6:
ES6 introduces computed property names, allowing the usage of expressions as property names:

<code class="javascript">var myVar = "name";
var myObject = {
    [myVar]: "value"
};</code>

In Pre-ES6:
Though not supported in object literals, you can dynamically assign properties with the [] syntax:

<code class="javascript">var myObject = {};
var myVar = "name";
myObject[myVar] = "value";</code>

The above is the detailed content of How Can I Use Variables as Property Names in JavaScript Objects?. 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