2017-05-30 128 views
0

我有一个动态创建的对象,有些时候它有属性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; 
} 

但因为没有expose我有以下错误Uncaught TypeError: Cannot set property '0' of undefined但它应该与= this.value正确创建它?

那么我该如何解决这个问题呢?

回答

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 
+0

我尝试这样,我回到这里之后 – Jerome

+0

对不起@Jerome,你说这没有奏效? –

+0

不,不,我测试你的答案,但我需要10分钟来测试 – Jerome

0

这里theCtns.services [ctn] .expose是未定义的,这就是为什么你得到这个错误。为了避免这种错误,您可以添加一个检查像

if(theCtns.services[ctn].expose) { 
    theCtns.services[ctn].expose[index] = this.value; 
} 

还是应该定义theCtns.services [箱] .expose值之前分配给它。