Home >Web Front-end >JS Tutorial >How Can I Use Variables as Object Keys in JavaScript Object Literals?
Using Variables as Object Keys in JavaScript Literals
In JavaScript, it is possible to define object literals using key-value pairs. However, when attempting to use a variable as a key, certain limitations exist.
Consider the following code snippet:
<something>.stop().animate({ 'top' : 10 }, 10);
This code successfully updates the "top" CSS property of an element. However, when trying to use a variable instead:
var thetop = 'top'; <something>.stop().animate({ thetop : 10 }, 10);
the code fails. The reason is that object literals require keys to be enclosed in either single or double quotes, while variable names cannot.
ES5 and Earlier:
In ES5 and earlier versions of JavaScript, there is no straightforward way to use variables as object keys directly. One workaround is to create an empty object literal and then assign the variable to the desired key:
var thetop = "top"; // Create the object literal var aniArgs = {}; // Assign the variable property name with a value of 10 aniArgs[thetop] = 10; // Pass the resulting object to the animate method <something>.stop().animate( aniArgs, 10 );
ES6 and Later:
ES6 introduces the ComputedPropertyName syntax, which allows the use of variable expressions as object keys:
var thetop = "top", obj = { [thetop]: 10 }; console.log(obj.top); // -> 10
This syntax allows for cleaner and more concise code, particularly when dealing with dynamic object keys. It is supported in modern versions of all major browsers.
The above is the detailed content of How Can I Use Variables as Object Keys in JavaScript Object Literals?. For more information, please follow other related articles on the PHP Chinese website!