如何在 JavaScript 对象文字中使用变量作为键? [英] How to use a variable for a key in a JavaScript object literal?

查看:40
本文介绍了如何在 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.

这篇关于如何在 JavaScript 对象文字中使用变量作为键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆