不能在一个对象

问题描述:

我的目标是动态设置,如姓名,隐蔽性和no_parent性能动态设置属性,但它一直给我:不能在一个对象

TypeError: Cannot set property 'name' of undefined

即使我通过参数传递之前,将初始化scorcroot

下面是代码:

adattamento: function(data) { 
    var continua = true; 
    var scorcfat = this.famiglia; 
    var scorcroot = {}; 
    this.controlloprimi(scorcroot, scorcfat); 
    this.root = scorcroot; 
    console.log("hey!") 
    console.log(this.root); 
    }, 
    controlloprimi: function(scorcroot, scorcfat) { 
    scorcroot.name = scorcfat.name; 
    scorcroot.hidden = false; 
    scorcroot.no_parent = true; 

    if (scorcfat.father != null) { 
     if (scorcfat.mother != null) { 
     scorcroot.children = [{}, {}, {}]; 
     this.controlloprimi(scorcroot.children[1], scorcfat.father); 
     scorcroot.children[2].name = ""; 
     scorcroot.children[2].hidden = true; 
     scorcroot.children[2].no_parent = false; 
     this.controlloprimi(scorcroot.children[3], scorcfat.mother) 
     } else { 
     scorcroot.children = [{}] 
     this.controlloprimi(scorcroot.children[1], scorcfat.father); 
     } 
    } 

    if (scorcfat.mother != null) { 
     scorcroot.children = [{}, {}]; 
     this.controlloprimi(scorcroot.children[1], scorcfat.mother); 
    } 
    }, 
+0

确保'scorcroot.children [2 ]'不是'undefined'。只是一个指针,JS中的索引从0开始,而不是1 – Rajesh

+0

是的问题是数字...谢谢 – ImFireblade

scorcroot.children[3]不是一个对象,你已经初始化了scorcroot.children阵列仅具有3个对象。所以scorcroot.children [3]是undefined并且你正在设置未定义的属性。

+0

非常感谢你 – ImFireblade

+0

嗨@ImFireblade请让我知道这是否适用于你,并接受答案if它的作品 –

+0

它的作品谢谢你! – ImFireblade

你的问题似乎是这条线

this.controlloprimi(scorcroot.children[3],scorcfat.mother) 

,因为你只有在这个数组初始化给定的3项

scorcroot.children=[{},{},{}]; 

这意味着scorcroot.children[3]undefined

不能确定的目的的代码,所以我只是建议让它4项而不是3

scorcroot.children=[{},{},{},{}]; 
+0

Omg太愚蠢了哈哈...谢谢你 – ImFireblade

问题是阵列的错误枚举.. 所以我在3个对象的数组,并通过调用阵列[3] i的调用第四未定义的对象