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

时间:2022-07-17 12:53:10

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属性传递给动画函数作为变量。

7 个解决方案

#1


434  

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


73  

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.

键可以是任何类型的表达式(如变量),返回一个值。

So here your code would look like:

你的代码是这样的:

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

Where thetop will be replaced by the variable value.

顶部将被变量值替换。

#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
  • StringLiteral
  • NumericLiteral
  • NumericLiteral

[...]

[…]

The production PropertyName : IdentifierName is evaluated as follows:

生产属性名:IdentifierName评估如下:

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

The production PropertyName : StringLiteral is evaluated as follows:

生产属性名:StringLiteral的计算结果如下:

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

The production PropertyName : NumericLiteral is evaluated as follows:

生产属性名称:NumericLiteral进行如下评估:

  1. Let nbr be the result of forming the value of the NumericLiteral.
  2. 让nbr是构成数字文字价值的结果。
  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'.

    属性名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).

    惟一的三个选项是标识符(扩展到字符串文字)、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.

键是新属性的名称。

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

传递给animate的属性的对象为{左: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


434  

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


73  

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.

键可以是任何类型的表达式(如变量),返回一个值。

So here your code would look like:

你的代码是这样的:

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

Where thetop will be replaced by the variable value.

顶部将被变量值替换。

#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
  • StringLiteral
  • NumericLiteral
  • NumericLiteral

[...]

[…]

The production PropertyName : IdentifierName is evaluated as follows:

生产属性名:IdentifierName评估如下:

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

The production PropertyName : StringLiteral is evaluated as follows:

生产属性名:StringLiteral的计算结果如下:

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

The production PropertyName : NumericLiteral is evaluated as follows:

生产属性名称:NumericLiteral进行如下评估:

  1. Let nbr be the result of forming the value of the NumericLiteral.
  2. 让nbr是构成数字文字价值的结果。
  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'.

    属性名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).

    惟一的三个选项是标识符(扩展到字符串文字)、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.

键是新属性的名称。

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

传递给animate的属性的对象为{左: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>