为什么下面的工作?
<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属性作为变量传递给动画函数。
当前回答
这样也可以实现预期的输出
var jsonobj={}; 变量计数=0; $(document).on('click','#btnadd', function() { jsonobj[count]=new Array({ “1” : $(“#txtone”).val()},{ “2” : $(“#txttwo”).val()}); 计数++; console.clear(); console.log(jsonobj); }); <script src=“https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js”></script> <span>值 1</span><输入 id=“txtone” 类型=“文本”/> <span>值 2</span><输入 id=“txttwo” 类型=“文本”/> <按钮 id=“btnadd”>添加</button>
其他回答
{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
您可以在每个主流浏览器的最新版本中使用这种新语法。
如果你想要对象键与变量名相同,在es2015有一个简短的手。 ECMAScript 2015中的新符号
var thetop = 10;
var obj = { thetop };
console.log(obj.thetop); // print 10
使用ECMAScript 2015,你现在可以直接在对象声明中使用括号表示:
var obj = {
[key]: value
}
其中key可以是返回值的任何类型的表达式(例如变量)。
你的代码看起来是这样的:
<something>.stop().animate({
[thetop]: 10
}, 10)
在被用作键之前,top将被计算。
您可以为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
)
2020年更新/ example.com ...
一个更复杂的例子,使用括号和字面量…您可能需要做一些事情,例如使用vue/axios。把文字用括号括起来,所以
['…]']
{
[`filter[${query.key}]`]: query.value, // 'filter[foo]' : 'bar'
}