Home > Web Front-end > JS Tutorial > How Do I Dynamically Assign Property Names in JavaScript Object Literals?

How Do I Dynamically Assign Property Names in JavaScript Object Literals?

Susan Sarandon
Release: 2024-12-23 04:20:22
Original
804 people have browsed it

How Do I Dynamically Assign Property Names in JavaScript Object Literals?

Understanding the Behavior of Object Literals in JavaScript

When working with object literals in JavaScript, developers may encounter situations where defining property names dynamically is desirable. However, this can lead to confusion if the intended behavior is not understood.

Consider the example provided:

<something>.stop().animate(
    { 'top' : 10 }, 10
);
Copy after login

In this case, the code successfully assigns the property 'top' to the value 10 within an object literal. This is because the property name is enclosed in single quotes, indicating a literal string as the property key.

In contrast, when using a variable as the property name:

var thetop = 'top';
<something>.stop().animate(
    { thetop : 10 }, 10
);
Copy after login

The code fails because JavaScript does not support dynamically generated property names for object literals in this manner. Prior to ES5, the only way to achieve this was to manually construct the object literal by assigning the value to a variable property name:

var thetop = "top";
var aniArgs = {};
aniArgs[thetop] = 10;
<something>.stop().animate(
    aniArgs, 10
);
Copy after login

However, with the introduction of ES6, developers now have access to Computed Property Names for object literals. Using this new syntax, property names can be dynamically specified as expressions enclosed in square brackets:

var thetop = "top";
var obj = { [thetop]: 10 };

console.log(obj.top); // -> 10
Copy after login

This syntax allows developers to create object literals with dynamically assigned property names, much like the original example with the literal string as the property key.

The above is the detailed content of How Do I Dynamically Assign Property Names in JavaScript Object Literals?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template