How to use a variable for a key in a JavaScript ob

2018-12-30 22:05发布

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.

9条回答
回忆,回不去的记忆
2楼-- · 2018-12-30 22:43

ES5 quote that says it should not work

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

PropertyName :

  • IdentifierName
  • StringLiteral
  • NumericLiteral

[...]

The production PropertyName : IdentifierName is evaluated as follows:

  1. Return the String value containing the same sequence of characters as the IdentifierName.

The production PropertyName : StringLiteral is evaluated as follows:

  1. Return the SV [String value] of the StringLiteral.

The production PropertyName : NumericLiteral is evaluated as follows:

  1. Let nbr be the result of forming the value of the NumericLiteral.
  2. Return ToString(nbr).

This means that:

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

    The PropertyName theTop is an IdentifierName, so it gets converted to the 'theTop' string value, which is the string value of '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).

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

查看更多
萌妹纸的霸气范
3楼-- · 2018-12-30 22:48

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}

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

查看更多
与风俱净
4楼-- · 2018-12-30 22:49

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>

查看更多
人气声优
5楼-- · 2018-12-30 22:52

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

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

查看更多
几人难应
6楼-- · 2018-12-30 22:55

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

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.

查看更多
裙下三千臣
7楼-- · 2018-12-30 22:55

You could do the following for ES5:

var theTop = 'top'
<something>.stop().animate(
  JSON.parse('{"' + theTop + '":' + JSON.stringify(10) + '}'), 10
)

Or extract to a function:

function newObj (key, value) {
  return JSON.parse('{"' + key + '":' + JSON.stringify(value) + '}')
}

var theTop = 'top'
<something>.stop().animate(
  newObj(theTop, 10), 10
)
查看更多
登录 后发表回答