Home >Web Front-end >JS Tutorial >How Do I Dynamically Assign Property Names in JavaScript Object Literals?
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 );
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 );
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 );
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
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!