javascript - 如何给对象添加属性?

标签 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 对吗?

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

最佳答案

所以我很确定您的问题是您需要先创建属性,然后为第一个索引分配一个值。

尝试替换这一行:

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

关于javascript - 如何给对象添加属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44255981/

相关文章:

javascript - React-Native map 数据并保存所有项目

Java 多线程对象

Java:在对象类内部创建数组?

c++ - 编译器在 C++ 中生成默认构造函数

java - 如何在 JavaFX 中实现派生只读属性/值?

javascript - 如何正确使用 if/else 结构从右侧动画新内容并通过向左滑动摆脱旧内容?

javascript - "Incremented"元素中的 CSS 类

java - 资源包中的键是否唯一?

php - ajax 和 php(或其他服务器语言),哪个更好?

java - 属性文件中的选择模式