Home >Web Front-end >JS Tutorial >Why Doesn't JavaScript Allow Dynamic Object Keys in Object Literals Directly?

Why Doesn't JavaScript Allow Dynamic Object Keys in Object Literals Directly?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-30 21:48:15900browse

Why Doesn't JavaScript Allow Dynamic Object Keys in Object Literals Directly?

JavaScript Object Key from Variable Conundrum

When using object literals in JavaScript, you may encounter a peculiar behavior where assigning a variable to a dynamic property key does not work. Consider these two code snippets:

<something>.stop().animate({ 'top': 10 }, 10); // Works
var thetop = 'top';
<something>.stop().animate({ thetop: 10 }, 10); // Doesn't work

Why the Discrepancy?

The first snippet successfully sets the "top" property of an object, utilizing the dot notation. However, the second snippet fails because JavaScript does not allow using variables to define dynamic object property names directly in object literals.

Solution in ES5 and Earlier

To assign dynamic property names from variables in ES5 and earlier, you must construct the object literal manually:

var thetop = "top";
var aniArgs = {};
aniArgs[thetop] = 10; // Assign value to variable property name
<something>.stop().animate(aniArgs, 10);

Solution in ES6 and Later

ES6 introduced "ComputedPropertyName" in object literal grammar, enabling the assignment of dynamic property names from variables directly:

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

This syntax is supported in the latest versions of major browsers.

The above is the detailed content of Why Doesn't JavaScript Allow Dynamic Object Keys in Object Literals Directly?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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