2017-09-22 31 views
0

我的目標是動態設置,如姓名,隱蔽性和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

回答

0

scorcroot.children[3]不是一個對象,你已經初始化了scorcroot.children陣列僅具有3個對象。所以scorcroot.children [3]是undefined並且你正在設置未定義的屬性。

+0

非常感謝你 – ImFireblade

+0

嗨@ImFireblade請讓我知道這是否適用於你,並接受答案if它的作品 –

+0

它的作品謝謝你! – ImFireblade

0

你的問題似乎是這條線

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

,因爲你只有在這個數組初始化給定的3項

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

這意味着scorcroot.children[3]undefined

不能確定的目的的代碼,所以我只是建議讓它4項而不是3

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

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

0

問題是陣列的錯誤枚舉.. 所以我在3個對象的數組,並通過調用陣列[3] i的調用第四未定義的對象