为什么下面的工作?
<something>.stop().animate(
{ 'top' : 10 }, 10
);
然而这是行不通的:
var thetop = 'top';
<something>.stop().animate(
{ thetop : 10 }, 10
);
更清楚地说:目前我还不能将CSS属性作为变量传递给动画函数。
为什么下面的工作?
<something>.stop().animate(
{ 'top' : 10 }, 10
);
然而这是行不通的:
var thetop = 'top';
<something>.stop().animate(
{ thetop : 10 }, 10
);
更清楚地说:目前我还不能将CSS属性作为变量传递给动画函数。
当前回答
2020年更新/ example.com ...
一个更复杂的例子,使用括号和字面量…您可能需要做一些事情,例如使用vue/axios。把文字用括号括起来,所以
['…]']
{
[`filter[${query.key}]`]: query.value, // 'filter[foo]' : 'bar'
}
其他回答
{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
您可以在每个主流浏览器的最新版本中使用这种新语法。
更新:正如一位评论者指出的那样,任何支持箭头函数的JavaScript版本都将支持({[myKey]:myValue}),所以这个答案没有实际的用例(事实上,它可能会在一些奇怪的角落情况下崩溃)。
不要使用下面列出的方法。
我不敢相信这还没有发布:使用匿名求值的箭头函数!
完全非侵入性,不会混淆名称空间,并且只需要一行:
myNewObj = ((k,v)=>{o={};o[k]=v;return o;})(myKey,myValue);
演示:
var myKey=“valueof_myKey”; var myValue=“valueof_myValue”; var myNewObj = ((k,v)=>{o={};o[k]=v;return o;})(myKey,myValue); console.log(myNewObj);
在不支持新的{[myKey]: myValue}语法的环境中很有用,比如- - - - - - - - - - - - - - - -我刚刚在我的Web开发控制台- firefox 72.0.1上进行了验证,发布于2020-01-08。我接受纠正;用括号括起来就行了。
(我确信你可能会有一些更强大/可扩展的解决方案,或者涉及到reduce的巧妙使用,但在这一点上,你可能会更好地将对象创建分解为自己的函数,而不是强制地将其全部内联)
这并不重要,因为OP在十年前就问过这个问题,但为了完整性,并证明它是如何正确回答上述问题的,我将在原始环境中展示这个问题:
var thetop = 'top';
<something>.stop().animate(
((k,v)=>{o={};o[k]=v;return o;})(thetop,10), 10
);
给定的代码:
var thetop = 'top';
<something>.stop().animate(
{ thetop : 10 }, 10
);
翻译:
var thetop = 'top';
var config = { thetop : 10 }; // config.thetop = 10
<something>.stop().animate(config, 10);
正如你所看到的,{thetop: 10}声明没有使用变量thetop。相反,它创建了一个具有名为thetop键的对象。如果你想让键值是顶部变量的值,那么你必须在顶部使用方括号:
var thetop = 'top';
var config = { [thetop] : 10 }; // config.top = 10
<something>.stop().animate(config, 10);
方括号语法已在ES6中引入。在JavaScript的早期版本中,您必须执行以下操作:
var thetop = 'top';
var config = (
obj = {},
obj['' + thetop] = 10,
obj
); // config.top = 10
<something>.stop().animate(config, 10);
我已经使用下面的方法来添加一个具有“动态”名称的属性到对象:
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}
这只是使用了其他答案所推荐的必需的[]符号,但是代码行数更少!
你也可以这样尝试:
Const arr = [{ “描述”:“星期四”, “数”:“1”, “日期”:“2019-12-05” }, { “描述”:“星期三”, “数”:“0”, “日期”:“2019-12-04” }) Const res = arr。Map (value => { 返回{[value.description]: {count: value。计数、日期:值。日期 }) console.log (res);