如何在 JavaScript 对象文字中使用变量作为键?

新手上路,请多包涵

为什么以下工作?

<something>.stop().animate(
    { 'top' : 10 }, 10
);

而这不起作用:

var thetop = 'top';
<something>.stop().animate(
    { thetop : 10 }, 10
);

为了更清楚:目前我无法将 CSS 属性作为变量传递给 animate 函数。

原文由 speendo 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 415
2 个回答

{ thetop : 10 } 是一个有效的对象字面量。该代码将创建一个对象,其属性名为 thetop ,其值为 10。以下两者相同:

 obj = { thetop : 10 };
 obj = { "thetop" : 10 };

在 ES5 及更早版本中,您不能将变量用作对象文字内的属性名称。您唯一的选择是执行以下操作:

 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 定义为对象文字语法的一部分,它允许您编写如下代码:

 var thetop = "top",
 obj = { [thetop]: 10 };

 console.log(obj.top); // -> 10

您可以在每个主流浏览器的最新版本中使用这种新语法。

原文由 Andy E 发布,翻译遵循 CC BY-SA 3.0 许可协议

使用 ECMAScript 2015 ,您现在可以在对象声明中使用方括号符号直接执行此操作:

 var obj = {
  [key]: value
}

其中 key 可以是返回值的任何类型的表达式(例如变量)。

所以在这里你的代码看起来像:

 <something>.stop().animate({
  [thetop]: 10
}, 10)

其中 thetop 将在用作密钥之前进行评估。

原文由 kube 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题