我有一个动态创建的对象,有时它的属性theCtns.services["example"].expose
是一个数组,有时它没有。这是正常的,这里没有错误。
然后我有一个方法:
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;
}
但是我有以下错误Uncaught TypeError: Cannot set property '0' of undefined
因为没有expose
但它应该使用= this.value
创建它吗?
那么我该如何解决这个问题呢?
答案 0 :(得分:1)
因此,我非常确定您的问题是您需要先创建属性,然后为第一个索引分配值。
尝试替换此行:
theCtns.services[ctn].expose[index] = this.value;
这两行:
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
答案 1 :(得分:0)
这里theCtns.services [ctn] .expose未定义,这就是你收到此错误的原因。要避免此错误,您可以添加支票,如
if(theCtns.services[ctn].expose) {
theCtns.services[ctn].expose[index] = this.value;
}
或者你应该在为它赋值之前定义theCtns.services [ctn] .expose。