美文网首页
使用JavaScript将对象转换为字符串

使用JavaScript将对象转换为字符串

作者: phpCN中文网 | 来源:发表于2019-10-10 10:22 被阅读0次

JavaScript如何将对象转换为字符串?下面本篇文章就来给大家介绍一下使用JavaScript将不同对象转换为字符串的方法,希望对大家有所帮助。

方法1:使用String()函数

String()函数将对象的值转换为字符串。

语法:

String(object)

示例:

<script> 

var bool_to_s1 = Boolean(0);

var bool_to_s2 = Boolean(1);

var num_to_s = 1234;

document.write( typeof( bool_to_s1)+"<br>");

document.write( typeof(String( bool_to_s1))+ "<br>");

document.write( typeof( bool_to_s2)+ "<br>"); 

document.write(typeof(String( bool_to_s2))+ "<br>"); 

document.write( typeof( num_to_s)+ "<br>"); 

document.write(typeof(String( num_to_s))+ "<br>"); 

</script>

输出:

boolean

string

boolean

string

number

string

方法2:使用JSON.stringify()

JSON.stringify()将javascript对象转换为通过Web服务器发送数据所需的字符串。

语法:

JSON.stringify(obj)

参数:可以是对象,数组。

示例:

<script>

var obj_to_str={ name: "GeeksForGeeks", city: "Noida", contact:2488 };

var myJSON = JSON.stringify(obj_to_str);

document.write(myJSON)

</script>

输出:

{"name":"GeeksForGeeks","city":"Noida","contact":2488}


以上就是本篇文章的详细内容,更多请关注php中文网其它相关文章!

相关文章

网友评论

      本文标题:使用JavaScript将对象转换为字符串

      本文链接:https://www.haomeiwen.com/subject/wzdopctx.html