[英]How to add a property to an object's property that is dynamically named
var aaa = new Object;
var bbb = 2;
var ccc = 5;
aaa[bbb].description = differentObject.ccc.description;
console.log(aaa.bbb.description); //will report "undefined"
what I need, is to create a property "description" for each new value of bbb and assign a value to it inside the object aaa.我需要的是为 bbb 的每个新值创建一个属性“描述”,并在 object aaa 中为其分配一个值。 (in my code, this, except the declaration of aaa) runs in a loop and bbb, ccc values change with each cycle).
(在我的代码中,除了 aaa 的声明之外)在一个循环中运行,并且 bbb、ccc 值随每个循环而变化)。
ab
is equivalent to a["b"]
so when you're doing aaa.bbb
you're not doing anything related to the bbb
variable. ab
等价于a["b"]
所以当你在做aaa.bbb
时,你没有做任何与bbb
变量相关的事情。
aaa[bbb].description
this is correct to set a property on aaa[bbb]
, however, aaa[bbb]
needs to be an object. aaa[bbb].description
在aaa[bbb]
上设置属性是正确的,但是aaa[bbb]
需要是 object。
An easier way do to this would be:一个更简单的方法是:
var aaa = {};
var bbb = 2;
var ccc = 5;
aaa[bbb] = {description: differentObject[ccc].description};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.