Home > Web Front-end > JS Tutorial > How Can I Use Variables as Keys in JavaScript Object Literals?

How Can I Use Variables as Keys in JavaScript Object Literals?

Susan Sarandon
Release: 2024-12-27 04:31:14
Original
833 people have browsed it

How Can I Use Variables as Keys in JavaScript Object Literals?

Dynamic Key-Value Assignment in JavaScript Object Literals

Despite its widespread use in animation, JavaScript poses a challenge when it comes to utilizing variables as keys within object literals. While syntax like ".stop().animate({ 'top' : 10 }, 10);" seamlessly assigns values to keys enclosed in quotes, attempting to employ variables as keys, as in "var thetop = 'top'; .stop().animate({ thetop : 10 }, 10);", meets with failure.

The Reason Behind the Discrepancy

{ thetop : 10 } constitutes a valid object literal syntax. The code instructs JavaScript to create an object with a property called thetop, assigning it a value of 10. Notably, both { thetop : 10 } and { "thetop" : 10 } produce identical object structures.

Circumventing the Limitation in ES5 and Earlier

Prior to ES6, leveraging variables as property names within object literals was impossible. The workaround involved creating an object literal first, followed by assigning values to its properties using the variable as the key, exemplified as:

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

ES6 and the Advent of Computed Property Names

ES6 revolutionized this landscape by introducing ComputedPropertyNames in object literal syntax. This advancement enables coding akin to:

var thetop = "top", obj = { [thetop]: 10 };
console.log(obj.top); // -> 10
Copy after login

This modernized syntax empowers developers to seamlessly use variables as property names in object literals across contemporary versions of mainstream browsers.

The above is the detailed content of How Can I Use Variables as Keys in JavaScript Object Literals?. For more information, please follow other related articles on the PHP Chinese website!

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