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

为何下面的工做? git

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

而这不起做用: es6

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

更清楚地说:目前,我没法将CSS属性做为变量传递给animate函数。 github


#1楼

我已使用如下内容向对象添加具备“动态”名称的属性: 浏览器

var key = 'top';
$('#myElement').animate(
   (function(o) { o[key]=10; return o;})({left: 20, width: 100}),
   10
);

key是新属性的名称。 函数

传递给animate的属性的对象将为{left: 20, width: 100, top: 10} spa

这只是使用其余答案所建议的必填[]表示法,可是用的代码行却更少! code


#2楼

{ thetop : 10 }是有效的对象文字。 该代码将建立一个名为thetop的对象,该对象的值为10。如下两项相同: 对象

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

在ES5和更早版本中,不能在对象文字中使用变量做为属性名称。 您惟一的选择是执行如下操做: ip

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

您能够在每一个主流浏览器的最新版本中使用此新语法。


#3楼

ES5引用说它不起做用

注意:ES6的规则已更改: https ://stackoverflow.com/a/2274327/895245

规格: http//www.ecma-international.org/ecma-262/5.1/#sec-11.1.5

PropertyName:

  • 标识符名称
  • 字符串字面量
  • 数值文学

[...]

生产PropertyName:IdentifierName的评估以下:

  1. 返回包含与IdentifierName相同的字符序列的String值。

生产PropertyName:StringLiteral的评估以下:

  1. 返回StringLiteral的SV [String value]。

生产PropertyName:NumericLiteral的评估以下:

  1. 令nbr为造成NumericLiteral值的结果。
  2. 返回ToString(nbr)。

这意味着:

  • { theTop : 10 }{ 'theTop' : 10 }

    所述PropertyName theTopIdentifierName ,所以它被转换到'theTop'字符串值,这是字符串值'theTop'

  • 没法使用变量键编写对象初始值设定项(文字)。

    仅有的三个选项是IdentifierName (扩展为字符串文字), StringLiteralNumericLiteral (也扩展为字符串)。


#4楼

使用ECMAScript 2015,您如今能够直接在对象声明中使用方括号表示法进行操做:

var obj = {
  [key]: value
}

其中key能够是任何返回值的表达式(例如,变量)。

所以,您的代码以下所示:

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

用做键以前将评估thetop


#5楼

在变量周围添加方括号对我来讲很好。 尝试这个

var thetop = 'top';
<something>.stop().animate(
    { [thetop] : 10 }, 10
);
相关文章
相关标签/搜索