2013-05-29 50 views
0

我遍歷從服務器返回的集合;它看起來像這樣:通過點符號訪問對象屬性

roster: Array 
    0: Object 
     avatar: null 
     contactName: "[email protected]" 
     contactType: "grouping" 
     displayName: "Joe Shmoe" 

我創建一個表,並試圖將「顯示名」添加到它,而是由點號訪問不能正常工作。我的代碼在下面有什麼問題?

function createAddressBook() 
      { 
       var tbl = document.getElementById('addressBook_tbl'); 

       var tbdy = document.createElement('tbody'); 

       // cells creation 
       for(var j = 0; j <= roster.length; j++) 
       { 
        // table row creation 
        var row = document.createElement("tr"); 

        for(var i = 0; i < 2; i++) 
        { 
         // create element <td> and text node 
         //Make text node the contents of <td> element 
         // put <td> at end of the table row 
         var cell = document.createElement("td");  
         var cellText = document.createTextNode(roster[ j ].displayName); 

         cell.appendChild(cellText); 
         row.appendChild(cell); 
        } 

        //row added to end of table body 
        tbdy.appendChild(row); 
       } 

       // append the <tbody> inside the <table> 
       tbl.appendChild(tbdy); 
      } 
+1

和我打賭,因爲你沒有使用'i'訪問它 – letiagoalves

回答

3

您使用j,當你定義i

// ----------------v-------should be `i` 
"user: " + roster[ j ].displayName 

僅供參考,您可以使用.insertCell(-1)附加新的細胞。

row.insertCell(-1) 
    .appendChild(document.createTextNode("user: " + roster[ j ].displayName)); 

編輯:當你更新代碼的工作,但它有一個錯誤。

您正嘗試訪問roster超過其最後一個索引的索引。因爲數組索引是從0開始的,所以最後一個索引是roster.length - 1,所以您應該使用<而不是<=

// ---------------v 
for(var j = 0; j < roster.length; j++) 
+0

對不起,剛剛更新了我原來的職位,因爲它沒有表現出以「J外環它不與方括號也工作「定義。 – fumeng

+1

然後你的代碼對我來說工作得很好。 http://jsfiddle.net/H2C8n/ – 2013-05-29 14:42:49

+0

@fumeng:你的代碼中有一個錯誤直到'roster'循環結束時纔會顯示出來。我更新了我的答案。 – 2013-05-29 14:46:04