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