通过点表示法访问对象属性

Access object property via dot notation

本文关键字:访问 对象 属性 表示      更新时间:2023-09-26

我正在迭代从服务器返回的集合;它看起来像这样:

roster: Array
    0: Object
        avatar: null
        contactName: "me@test.com"
        contactType: "grouping"
        displayName: "Joe Shmoe"

我正在创建一个表,并试图将"displayName"添加到它,但通过点表示法访问不工作。我下面的代码有什么问题?

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 );
            }

当您定义i时,您正在使用j

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

仅供参考,您可以使用.insertCell(-1)附加一个新单元格。

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

EDIT:当你更新的代码工作时,它确实有一个错误。

您正在尝试访问roster在其上一个索引之外的索引。因为Array的索引是从0开始的,所以最后一个索引是roster.length - 1,所以应该使用<而不是<=

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