[英]How to add property to an object?
I have an object who is created dynamically and some times it has the property theCtns.services["example"].expose
who is an array and some times it hasn't. 我有一个动态创建的对象,有时它具有属性
theCtns.services["example"].expose
谁是数组,有时却不是。 It's normal there is no bugs here. 正常,这里没有错误。
Then I have a method that do: 然后我有一个方法可以做到:
if($('#labelExpose').children().length > 1){
$('#labelExpose').children('input').each(function (index) {
if(this.value){
console.log("value of expose field number:" + index );
console.log(this.value);
theCtns.services[ctn].expose[index] = this.value;
}
});
}else{
delete theCtns.services[ctn].depends_on;
}
But I have the following error Uncaught TypeError: Cannot set property '0' of undefined
because there isn't expose
but it should creates it with the = this.value
right ? 但是我
Uncaught TypeError: Cannot set property '0' of undefined
以下错误Uncaught TypeError: Cannot set property '0' of undefined
因为没有expose
但应该使用= this.value
对吗?
So how can I resolve this problem ? 那么我该如何解决这个问题呢?
So I'm pretty sure your issue is that you need to create the property first and then assign a value to the first index. 因此,我很确定您的问题是您需要先创建属性,然后将值分配给第一个索引。
Try replacing this line: 尝试替换此行:
theCtns.services[ctn].expose[index] = this.value;
With these two lines: 用这两行:
theCtns.services[ctn].expose = theCtns.services[ctn].expose || []; // if it already exists, it will set it to itself, if not it will set it to an empty array
theCtns.services[ctn].expose[index] = this.value; // this will not set the item at that index
Here theCtns.services[ctn].expose is undefined, that is why you are getting this error. 这里的Ctns.services [ctn] .expose是未定义的,这就是为什么您会收到此错误。 To avoid this error you can add a check like
为避免此错误,您可以添加类似的支票
if(theCtns.services[ctn].expose) {
theCtns.services[ctn].expose[index] = this.value;
}
Or you should define theCtns.services[ctn].expose before assign a value to it. 或者,您应该在分配值之前定义theCtns.services [ctn] .expose。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.