从字符串声明属性名称[重复]

Posted

技术标签:

【中文标题】从字符串声明属性名称[重复]【英文标题】:Declare property name from string [duplicate] 【发布时间】:2020-12-16 14:20:17 【问题描述】:

我有这个

oArray = ;
aProperty = "Property1";
aValue = "Value1";

有什么方法可以使用 aProperty 值作为数组中的对象名称?这是期望的结果:

oArray = 
  Property1: "Value1"
;

提前致谢和问候

【问题讨论】:

使用oArray = [aProperty]: aValue。这称为computed property。 成功了,谢谢。 IDE 抱怨语法,但最终它执行没有问题 【参考方案1】:

就这么简单

var oArray = ;
var aProperty = "Property1";
var aValue = "Value1";

oArray[aProperty] = aValue;
console.log(oArray)

【讨论】:

【参考方案2】:

是这样的:

aProperty = "Property1";
aValue = "Value1";
oArray = [aProperty]: aValue;

【讨论】:

以上是关于从字符串声明属性名称[重复]的主要内容,如果未能解决你的问题,请参考以下文章