2017-05-30 20 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

私はあなたの問題が最初にプロパティを作成してから、最初のインデックスに値を割り当てる必要があることを確認しています。

このラインを交換してみてください:

これら2行の
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は[CTN] .expose前にそれに値を割り当てる定義する必要があります。

関連する問題