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
Release: 2024-12-30 21:48:15
Original
911 people have browsed it

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
Copy after login

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);
Copy after login

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
Copy after login

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!

source:php.cn
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