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

时间:2021-10-23 12:53:01

Why does the following work?

为什么以下工作?

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

Whereas this doesn't work:

虽然这不起作用:

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

To make it even clearer: At the moment I'm not able to pass a CSS property to the animate function as a variable.

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

7 个解决方案

#1


442  

{ 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:

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

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

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:

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

var thetop = "top";// create the object literalvar aniArgs = {};// Assign the variable property name with a value of 10aniArgs[thetop] = 10; // Pass the resulting object to the animate method<something>.stop().animate(    aniArgs, 10  );  

ES6 defines ComputedPropertyName as part of the grammar for object literals, which allows you to write the code like this:

ES6将ComputedPropertyName定义为对象文字语法的一部分,它允许您编写如下代码:

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.

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

#2


77  

With ECMAScript 2015 you are now able to do it directly in object declaration with the brackets notation: 

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

var obj = {  [key]: value}

Where key can be any sort of expression (e.g. a variable) returning a value.

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

So here your code would look like:

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

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

Where thetop will be replaced by the variable value.

其中thetop将被变量值替换。

#3


8  

ES5 quote that says it should not work

ES5引用说它应该不起作用

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

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

PropertyName :

PropertyName:

  • IdentifierName
  • IdentifierName
  • StringLiteral
  • 字符串字面量
  • NumericLiteral
  • NumericLiteral

[...]

[...]

The production PropertyName : IdentifierName is evaluated as follows:

生产PropertyName:IdentifierName的计算方法如下:

  1. Return the String value containing the same sequence of characters as the IdentifierName.
  2. 返回包含与IdentifierName相同的字符序列的String值。

The production PropertyName : StringLiteral is evaluated as follows:

生产PropertyName:StringLiteral的计算方法如下:

  1. Return the SV [String value] of the StringLiteral.
  2. 返回StringLiteral的SV [String value]。

The production PropertyName : NumericLiteral is evaluated as follows:

生产PropertyName:NumericLiteral的计算方法如下:

  1. Let nbr be the result of forming the value of the NumericLiteral.
  2. 设nbr是形成NumericLiteral值的结果。
  3. Return ToString(nbr).
  4. 返回ToString(nbr)。

This means that:

这意味着:

  • { theTop : 10 } is the exact same as { 'theTop' : 10 }

    {theTop:10}与{'theTop':10}完全相同

    The PropertyName theTop is an IdentifierName, so it gets converted to the 'theTop' string value, which is the string value of 'theTop'.

    PropertyName theTop是一个IdentifierName,因此它被转换为'theTop'字符串值,这是'theTop'的字符串值。

  • It is not possible to write object initializers (literals) with variable keys.

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

    The only three options are IdentifierName (expands to string literal), StringLiteral, and NumericLiteral (also expands to a string).

    只有三个选项是IdentifierName(扩展为字符串文字),StringLiteral和NumericLiteral(也扩展为字符串)。

Rules have changed for ES6: https://*.com/a/2274327/895245

ES6的规则已更改:https://*.com/a/2274327/895245

#4


3  

I have used the following to add a property with a "dynamic" name to an object:

我使用以下内容向对象添加具有“动态”名称的属性:

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

key is the name of the new property.

key是新属性的名称。

The object of properties passed to animate will be {left: 20, width: 100, top: 10}

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

This is just using the required [] notation as recommended by the other answers, but with fewer lines of code!

这只是使用其他答案推荐的所需[]表示法,但代码行数较少!

#5


2  

Adding square bracket around the variable works good for me. Try this

在变量周围添加方括号对我来说很有用。尝试这个

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

#6


0  

Given code:

给定代码:

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

Translation:

翻译:

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

As you can see, the { thetop : 10 } declaration doesn't make use of the variable thetop. Instead it creates an object with a key named thetop. If you want the key to be the value of the variable thetop, then you will have to use square brackets around thetop:

如您所见,{thetop:10}声明不使用变量thetop。相反,它使用名为thetop的键创建一个对象。如果你想要键是变量thetop的值,那么你将不得不在顶部周围使用方括号:

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

The square bracket syntax has been introduced with ES6. In earlier versions of JavaScript, you would have to do the following:

ES6引入了方括号语法。在早期版本的JavaScript中,您必须执行以下操作:

var thetop = 'top';var config = (  obj = {},  obj['' + thetop] = 10,  obj); // config.top = 10<something>.stop().animate(config, 10);

#7


0  

This way also you can achieve desired output

这样你也可以实现所需的输出

var jsonobj={};var count=0;$(document).on('click','#btnadd', function() {    jsonobj[count]=new Array({ "1"  : $("#txtone").val()},{ "2"  : $("#txttwo").val()});    count++;    console.clear();    console.log(jsonobj);});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><span>value 1</span><input id="txtone" type="text"/><span>value 2</span><input id="txttwo" type="text"/><button id="btnadd">Add</button>

#1


442  

{ 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:

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

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

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:

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

var thetop = "top";// create the object literalvar aniArgs = {};// Assign the variable property name with a value of 10aniArgs[thetop] = 10; // Pass the resulting object to the animate method<something>.stop().animate(    aniArgs, 10  );  

ES6 defines ComputedPropertyName as part of the grammar for object literals, which allows you to write the code like this:

ES6将ComputedPropertyName定义为对象文字语法的一部分,它允许您编写如下代码:

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.

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

#2


77  

With ECMAScript 2015 you are now able to do it directly in object declaration with the brackets notation: 

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

var obj = {  [key]: value}

Where key can be any sort of expression (e.g. a variable) returning a value.

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

So here your code would look like:

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

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

Where thetop will be replaced by the variable value.

其中thetop将被变量值替换。

#3


8  

ES5 quote that says it should not work

ES5引用说它应该不起作用

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

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

PropertyName :

PropertyName:

  • IdentifierName
  • IdentifierName
  • StringLiteral
  • 字符串字面量
  • NumericLiteral
  • NumericLiteral

[...]

[...]

The production PropertyName : IdentifierName is evaluated as follows:

生产PropertyName:IdentifierName的计算方法如下:

  1. Return the String value containing the same sequence of characters as the IdentifierName.
  2. 返回包含与IdentifierName相同的字符序列的String值。

The production PropertyName : StringLiteral is evaluated as follows:

生产PropertyName:StringLiteral的计算方法如下:

  1. Return the SV [String value] of the StringLiteral.
  2. 返回StringLiteral的SV [String value]。

The production PropertyName : NumericLiteral is evaluated as follows:

生产PropertyName:NumericLiteral的计算方法如下:

  1. Let nbr be the result of forming the value of the NumericLiteral.
  2. 设nbr是形成NumericLiteral值的结果。
  3. Return ToString(nbr).
  4. 返回ToString(nbr)。

This means that:

这意味着:

  • { theTop : 10 } is the exact same as { 'theTop' : 10 }

    {theTop:10}与{'theTop':10}完全相同

    The PropertyName theTop is an IdentifierName, so it gets converted to the 'theTop' string value, which is the string value of 'theTop'.

    PropertyName theTop是一个IdentifierName,因此它被转换为'theTop'字符串值,这是'theTop'的字符串值。

  • It is not possible to write object initializers (literals) with variable keys.

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

    The only three options are IdentifierName (expands to string literal), StringLiteral, and NumericLiteral (also expands to a string).

    只有三个选项是IdentifierName(扩展为字符串文字),StringLiteral和NumericLiteral(也扩展为字符串)。

Rules have changed for ES6: https://*.com/a/2274327/895245

ES6的规则已更改:https://*.com/a/2274327/895245

#4


3  

I have used the following to add a property with a "dynamic" name to an object:

我使用以下内容向对象添加具有“动态”名称的属性:

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

key is the name of the new property.

key是新属性的名称。

The object of properties passed to animate will be {left: 20, width: 100, top: 10}

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

This is just using the required [] notation as recommended by the other answers, but with fewer lines of code!

这只是使用其他答案推荐的所需[]表示法,但代码行数较少!

#5


2  

Adding square bracket around the variable works good for me. Try this

在变量周围添加方括号对我来说很有用。尝试这个

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

#6


0  

Given code:

给定代码:

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

Translation:

翻译:

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

As you can see, the { thetop : 10 } declaration doesn't make use of the variable thetop. Instead it creates an object with a key named thetop. If you want the key to be the value of the variable thetop, then you will have to use square brackets around thetop:

如您所见,{thetop:10}声明不使用变量thetop。相反,它使用名为thetop的键创建一个对象。如果你想要键是变量thetop的值,那么你将不得不在顶部周围使用方括号:

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

The square bracket syntax has been introduced with ES6. In earlier versions of JavaScript, you would have to do the following:

ES6引入了方括号语法。在早期版本的JavaScript中,您必须执行以下操作:

var thetop = 'top';var config = (  obj = {},  obj['' + thetop] = 10,  obj); // config.top = 10<something>.stop().animate(config, 10);

#7


0  

This way also you can achieve desired output

这样你也可以实现所需的输出

var jsonobj={};var count=0;$(document).on('click','#btnadd', function() {    jsonobj[count]=new Array({ "1"  : $("#txtone").val()},{ "2"  : $("#txttwo").val()});    count++;    console.clear();    console.log(jsonobj);});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><span>value 1</span><input id="txtone" type="text"/><span>value 2</span><input id="txttwo" type="text"/><button id="btnadd">Add</button>