简体   繁体   中英

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. 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 ?

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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM