如何向对象添加属性?

时间:2017-05-30 07:22:17

标签: javascript object properties

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

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

2 个答案:

答案 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。