[英]Literal or expression to create an object with a string-valued property name
The following code creates an object in which the property name is set at runtime: 以下代码创建一个在运行时设置属性名称的对象:
let pn = "xyz", ob = {}
op[pn] = 999
Is there any way to do that in a single step, as either a literal or an expression, and avoid the explicit assignment? 有没有办法在一个步骤中做到这一点,无论是文字还是表达式,都可以避免显式赋值?
let pn = "xyz", ob = { <clever stuff goes in here> }
[Obviously I could write my own function, but where's the fun in that?] [显然,我可以编写自己的函数,但是这样做的乐趣在哪里?]
How about that by just using brackets []
? 仅使用方括号
[]
怎么样?
/* // old way :) let pn = "xyz", ob = {} ob[pn] = 999 console.log(ob) */ //clever stuff goes here :) let pn = "xyz", ob = { [pn]:999 } console.log(ob)
You can define key with in the object like this 您可以像这样在对象中定义键
let obj={[pn="Xyz"]:999}
console.log(obj);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.