Home >Web Front-end >JS Tutorial >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 "
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);
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
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!