如何在 JavaScript 对象文字中使用变量作为键?
为什么以下工作有效?
<something>.stop().animate(
{ 'top' : 10 }, 10
);
而这不起作用:
var thetop = 'top';
<something>.stop().animate(
{ thetop : 10 }, 10
);
为了更清楚:目前我无法将 CSS 属性作为变量传递给 animate 函数.
To make it even clearer: At the moment I'm not able to pass a CSS property to the animate function as a variable.
推荐答案
{ thetop : 10 }
是一个有效的对象字面量.该代码将创建一个对象,其属性名为 thetop
,其值为 10.以下两者相同:
{ thetop : 10 }
is a valid object literal. The code will create an object with a property named thetop
that has a value of 10. Both the following are the same:
obj = { thetop : 10 };
obj = { "thetop" : 10 };
在 ES5 及更早版本中,您不能将变量用作对象字面量中的属性名称.您唯一的选择是执行以下操作:
In ES5 and earlier, you cannot use a variable as a property name inside an object literal. Your only option is to do the following:
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 定义 ComputedPropertyName 作为对象文字语法的一部分,它允许您编写如下代码:
ES6 defines ComputedPropertyName as part of the grammar for object literals, which allows you to write the code like this:
var thetop = "top",
obj = { [thetop]: 10 };
console.log(obj.top); // -> 10
您可以在每个主流浏览器的最新版本中使用这种新语法.
You can use this new syntax in the latest versions of each mainstream browser.
相关文章