2014-01-23 69 views
0

我想用JavaScript打印對象的數據。通過定義一個函數並調用該函數,我可以做到這一點。要調用這樣的功能,我在我的代碼中使用了s.show()。但我想要的是...只需指定s [如document.write(s)],我想打印該對象。在Java語言中,當我們嘗試打印一個對象時,System.out.println()在該對象上調用toString()方法。 JavaScript有什麼方法嗎?用javascript打印對象與我們用Java打印對象的方式相似

請幫忙。提前致謝。

<script> 
function stud(a,b,c) 
{ 
    this.one=a; 
    this.two=b; 
    this.three=c; 
    this.show=function toString() 
    { 
     document.write(a+","+b+","+c+"<br>"); 
    } 
} 
var s=new stud("smile","laugh","cry"); 
s.show(); // this is working 
document.write(s); // i want this also work same 
</script> 
+1

如果你需要做只是爲了記錄的目的,考慮'的console.log(S)'。 –

+0

'document.write(JSON.stringify(s));' –

+0

JSON.stringify()顯示對象的**屬性**和**值**但我只想要打印的值。任何幫助? – PoornaChandra

回答

1

您可以使用其日誌功能打印任何Javascript對象。

有基本的三個功能登錄電子

console.log(s); // You can use this one. 

或者你也可以解析你的對象是這樣的。

function stud(a,b,c) 
{ 
    this.one=a; 
    this.two=b; 
    this.three=c; 
    this.show=function toString() 
    { 
    // This will print your json as string as print in JAVA. 
    document.write(JSON.stringify(this)); 
    } 
} 

輸入:

var s=new stud("smile","laugh","cry"); 
s.show(); // this is working 

輸出:

{"one":"smile","two":"laugh","three":"cry"} 
+0

JSON.stringify()顯示對象的**屬性**和**值**。但我只想要對象的**值**。我的意思是,當我嘗試向用戶顯示對象(使用'docuement.write(s)')時,應調用我的code_的_toString()。 – PoornaChandra