[英]How to create 2nd level property with for JS object using bracketss
Here's deal. 这是交易。 I'm starting with an object literal.
我从对象文字开始。
var prepObj = {};
Then I will be doing a foreach where I'll be adding properties to this object. 然后,我将在foreach中向该对象添加属性。 Basically, in the end it will look something like this (on a larger scale).
基本上,最终它将看起来像这样(更大范围)。
{
34 : {
prop1: myvalue,
prop2: myvalue,
}
87 : {
prop1: myvalue,
prop2: myvalue,
}
102 : {
prop1: myvalue,
prop2: myvalue,
}
}
Throughout the loop I'll be finding a value for a certain property of a certain index (such as prop1 of 87), and creating it for the object. 在整个循环中,我将为某个索引的某个属性(例如87的prop1)找到一个值,并为该对象创建它。
So, before the loop I'm starting with a blank object. 因此,在循环之前,我从一个空白对象开始。
Then during the loop, I thought I could do: 然后在循环中,我想我可以做:
var index_id = 87;
var which_prop = "prop1";
var prop_value = "This is a value.";
prepObj[index_id][which_prop] = prop_value;
but when I try this I get an error saying: 但是当我尝试这个时,我收到一条错误消息:
Uncaught TypeError: Cannot set property 'prop1' of undefined
What am I doing wrong? 我究竟做错了什么?
JavaScript does not support autovivication . JavaScript不支持自动生存 。 You must define
prepObj[index_id] = {}
before you define prepObj[index_id][which_prop] = prop_value
. 在定义
prepObj[index_id][which_prop] = prop_value
之前,必须先定义prepObj[index_id] = {}
。
This is because prepObj[index_id]
is initially not defined. 这是因为最初未定义
prepObj[index_id]
。 Thus, you are trying to set the prop1
property on prepObj[index_id]
which is undefined
. 因此,您试图在
prepObj[index_id]
上设置prop1
属性,该属性undefined
。 You avoid this by making prepObj[index_id]
some defined value. 通过使
prepObj[index_id]
一些定义的值可以避免这种情况。
If you're worried about clobbering prepObj[index_id]
with a new object each time, you can test that the value is already set by either: 如果您担心每次都会用新对象破坏
prepObj[index_id]
,则可以通过以下任一方法测试该值是否已设置:
index_id in prepObj
- this tests that prepObj already has an entry whose key is the value of index_id
index_id in prepObj
测试prepObj是否已经有一个条目,其键为index_id
的值
typeof prepObj[index_id] != "undefined"
- this tests if the value of prepObj[index_id]
is not undefined
typeof prepObj[index_id] != "undefined"
-测试prepObj[index_id]
的值是否undefined
prepObj[index_id] || {}
prepObj[index_id] || {}
- this evaluates to prepObj[index_id]
if it's not a falsy value (like undefined
); prepObj[index_id] || {}
-如果它不是伪造的值(如undefined
),则其值为prepObj[index_id]
; otherwise it evaluates to a new object 否则将评估为一个新对象
Try this: 尝试这个:
prepObj[index_id] = {};
prepObj[index_id][which_prop] = prop_value;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.