为什么下面的工作?

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

然而这是行不通的:

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

更清楚地说:目前我还不能将CSS属性作为变量传递给动画函数。


当前回答

您可以为ES5执行以下操作:

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

或提取为一个函数:

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

var theTop = 'top'
<something>.stop().animate(
  newObj(theTop, 10), 10
)

其他回答

{thetop: 10}是一个有效的对象字面值。这段代码将创建一个属性为thetop的对象,值为10。以下两种情况相同:

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

在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将ComputedPropertyName定义为对象字面量语法的一部分,这允许你像这样编写代码:

var thetop = "top",
    obj = { [thetop]: 10 };

console.log(obj.top); // -> 10

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

你也可以这样尝试:

Const arr = [{ “描述”:“星期四”, “数”:“1”, “日期”:“2019-12-05” }, { “描述”:“星期三”, “数”:“0”, “日期”:“2019-12-04” }) Const res = arr。Map (value => { 返回{[value.description]: {count: value。计数、日期:值。日期 }) console.log (res);

ES6 / 2020

如果你试图使用“key:value”从任何其他来源将数据推入对象,你可以使用这样的方法:

let obj = {}
let key = "foo"
let value = "bar"

obj[`${key}`] = value

// A `console.log(obj)` would return:
// {foo: "bar}

// A `typeof obj` would return:
// "object"

希望这能帮助到一些人:)

我已经使用下面的方法来添加一个具有“动态”名称的属性到对象:

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}

这只是使用了其他答案所推荐的必需的[]符号,但是代码行数更少!

您可以为ES5执行以下操作:

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

或提取为一个函数:

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

var theTop = 'top'
<something>.stop().animate(
  newObj(theTop, 10), 10
)