2014-01-23 68 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