2013-03-17 57 views
-1

我想用這個末
化名
重新

在屏幕上顯示,但我想使用這個變量意見,我不麻煩知道如何使用它。的Javascript:與[Object對象]

var comments=[{"comment": "re", "author": "Anonym", "likes": 0, "key": "ahFzfmVhc3ljb21tZW50LWhyZHIQCxIHQ29tbWVudBj46qcJDA", "date": 1363460164.0, "approved": true}] 

for(i=0;i<1;i++){ 
     document.write(comments[i]+"") ; 
    } 

如果寫這個,只有在瀏覽器上寫有[Object object]。

回答

0

應該是:

for(var i=0;i<1;i++){ 
    console.log(comments[i].author + "\n" + comments[i].comment); //for author & comment 
} 

OR

for(var i=0;i<comments.length;i++){ 
    console.log(comments[i].author + "\n" + comments[i].comment); //for author & comment 
} 
0

其一,您的變量包含有一個元件,這是一個對象的陣列。

因此,爲了訪問內容,你必須使用comments[ INDEX ][ PROPERTYNAME ]這樣的:

var comments=[{"comment": "re", "author": "Anonym", "likes": 0, "key": "ahFzfmVhc3ljb21tZW50LWhyZHIQCxIHQ29tbWVudBj46qcJDA", "date": 1363460164.0, "approved": true}] 

for(i=0;i<1;i++){ 
    document.write(comments[i]['author'] + "<br>" + comments[i]['comment']) ; 
} 

一般來說,我會代替document.write()別的東西,這使得使用innerHTML。這可能是這樣的:

<div id="commentBox"></div> 
<script> 
    var comments=[{"comment": "re", "author": "Anonym", "likes": 0, "key": "ahFzfmVhc3ljb21tZW50LWhyZHIQCxIHQ29tbWVudBj46qcJDA", "date": 1363460164.0, "approved": true}], 
     commentBox = document.getElementById('commentBox'); 

    for(i=0;i<1;i++){ 
     commentBox.innerHTML += comments[i]['author'] + "<br>" + comments[i]['comment']; 
    } 
</script> 
0

對象屬性可以通過名稱來訪問:

document.write(comments[0].comment); 

如果你想整個對象,你可以使用JSON.stringify

document.write(JSON.stringify(comments[0])); 

要不明確格式化你想要的屬性:

document.write(comments[0].comment + ", " + comments[0].author); 
相關問題