spe*_*ndo 345 javascript variables jquery properties object-literal
为什么以下工作?
<something>.stop().animate(
{ 'top' : 10 }, 10
);
Run Code Online (Sandbox Code Playgroud)
虽然这不起作用:
var thetop = 'top';
<something>.stop().animate(
{ thetop : 10 }, 10
);
Run Code Online (Sandbox Code Playgroud)
为了使它更清晰:目前我无法将CSS属性作为变量传递给animate函数.
And*_*y E 590
{ thetop : 10 }
是一个有效的对象文字.代码将创建一个对象,其属性名为thetop
值10,以下两者相同:
obj = { thetop : 10 };
obj = { "thetop" : 10 };
Run Code Online (Sandbox Code Playgroud)
在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
);
Run Code Online (Sandbox Code Playgroud)
ES6 将 ComputedPropertyName 定义为对象文字语法的一部分,它允许您编写如下代码:
var thetop = "top",
obj = { [thetop]: 10 };
console.log(obj.top); // -> 10
Run Code Online (Sandbox Code Playgroud)
您可以在每个主流浏览器的最新版本中使用此新语法.
kub*_*ube 108
使用ECMAScript 2015,您现在可以使用括号表示法直接在对象声明中执行此操作:
var obj = {
[key]: value
}
Run Code Online (Sandbox Code Playgroud)
哪里key
可以是任何类型的表达式(例如变量)返回值.
所以这里你的代码看起来像:
<something>.stop().animate({
[thetop]: 10
}, 10)
Run Code Online (Sandbox Code Playgroud)
哪里thetop
将被变量值取代.
Cir*_*四事件 16
ES5引用说它应该不起作用
规格:http://www.ecma-international.org/ecma-262/5.1/#sec-11.1.5
PropertyName:
- IdentifierName
- 字符串字面量
- NumericLiteral
[...]
生产PropertyName:IdentifierName的计算方法如下:
- 返回包含与IdentifierName相同的字符序列的String值.
生产PropertyName:StringLiteral的计算方法如下:
- 返回StringLiteral的SV [String value].
生产PropertyName:NumericLiteral的计算方法如下:
- 设nbr是形成NumericLiteral值的结果.
- 返回ToString(nbr).
这意味着:
{ theTop : 10 }
与...完全相同 { 'theTop' : 10 }
的PropertyName
theTop
是一个IdentifierName
,所以它被转换为'theTop'
字符串值,这是的字符串值'theTop'
.
无法使用变量键编写对象初始值设定项(文字).
只有三个选项IdentifierName
(扩展为字符串文字)StringLiteral
,和NumericLiteral
(也扩展为字符串).
ES6的规则已更改:https://stackoverflow.com/a/2274327/895245
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"
Run Code Online (Sandbox Code Playgroud)
希望这对某人有所帮助:)
我使用以下内容向对象添加具有"动态"名称的属性:
var key = 'top';
$('#myElement').animate(
(function(o) { o[key]=10; return o;})({left: 20, width: 100}),
10
);
Run Code Online (Sandbox Code Playgroud)
key
是新属性的名称.
传递给的属性的对象animate
将是{left: 20, width: 100, top: 10}
这只是使用[]
其他答案推荐的必需符号,但代码行数较少!
小智 5
在变量周围添加方括号对我很有用。尝试这个
var thetop = 'top';
<something>.stop().animate(
{ [thetop] : 10 }, 10
);
Run Code Online (Sandbox Code Playgroud)
你也可以这样尝试:
const arr = [{
"description": "THURSDAY",
"count": "1",
"date": "2019-12-05"
},
{
"description": "WEDNESDAY",
"count": "0",
"date": "2019-12-04"
}]
const res = arr.map(value => {
return { [value.description]: { count: value.count, date: value.date } }
})
console.log(res);
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
131761 次 |
最近记录: |