2013-11-22 95 views
0
 $(document).ready(function() { 
    function Group(label, children) { 
         this.label = ko.observable(label); 
         this.children = ko.observableArray(children); 
        } 

     function getGroups() { 
         var grps = [ 
          [new Group("Group 1", [])], 
          [new Group("Group 2", [])] 
         ]; 
         for (var a in grps) { 
          alert(a.toString()); // works, alerts index 
          alert(a.label()); // doesn't works. should give Group label 
         } 
         return grps; 
        } 
getgroups(); 
    }); 

當我嘗試調用getGroups()函數警報不起作用。我不知道似乎是什麼問題。無法從JavaScript類獲得價值

回答

1

請使用

alert((grps[a])[0].label) 

原因:

  • for in遍歷屬性鍵。在你的例子中,grps數組的所有索引 。
  • 達到存儲在GRPS陣列使用GRPS對象並[a]

如何有關聲明它喜歡:

var grps = [ 
       new Group("Group 1", []), 
       new Group("Group 2", []) 
      ]; 

,然後使用

alert(grps[a].label) 

它是更大量可讀

+0

現在它只顯示未定義。 – Ruchan

+0

哦,只是注意到你正在將數組插入到grps數組中。你需要使用'alert((grps [a])[0] .label)' – closure

+0

哦,現在我明白了...爲什麼它不工作。這是因爲'this'修飾符實際上不是'Group'的文檔。 – Ruchan