简体   繁体   English

用于创建具有字符串值属性名称的对象的文字或表达式

[英]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.

相关问题 在Javascript中切片数组的每个字符串值元素 - Slice each string-valued element of an array in Javascript 可以在JavaScript对象文字中使用“创建”作为属性名称吗? - Is it okay to use “create” as a property name in a JavaScript object literal? 检查对象文字属性的名称 - check the name of an object literal property 字符串值函数的JavaScript typeof运算符返回“ function”而不是“ string” - Javascript typeof operator on string-valued function returns “function” instead of “string” 从嵌套对象文字返回属性名称 - Return the property name from a nested object literal 从对象文字字符串创建对象 - Create object from object literal string 如何在运行时通过字符串串联创建函数或对象属性名称? - How to create a function or object property name in runtime via string concatenation? Javascript:获取Object Literal中当前对象属性的名称 - Javascript: Get Name of Current Object Property in Object Literal 类型文字中的计算属性名称必须引用类型为文字类型或“唯一符号”类型的表达式 - A computed property name in a type literal must refer to an expression whose type is a literal type or a 'unique symbol' type 对象字面量中属性名称周围的方括号是什么意思? - What do square brackets around a property name in an object literal mean?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM