您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息

浅谈JS中String()与 .toString()的区别

2025/7/19 9:42:07发布14次查看
我们知道string()与 .tostring()都是可以转换为字符串类型,但是string()与 .tostring()的还是有区别的
1、.tostring()可以将所有的的数据都转换为字符串,但是要排除null 和 undefined
例如将false转为字符串类型
<script> var str = false.tostring(); console.log(str, typeof str); </script>
返回的结果为 false,string
看看null 和 undefined能不能转换为字符串
<blockquote style="margin-right: 0px;" dir="ltr"><pre class="html" name="code"><script> var str = null.tostring(); console.log(str, typeof str); </script>
结果程序报错
<script> var str = undefined.tostring(); console.log(str, typeof str); </script>
程序也报错
.tostring() 括号中的可以写一个数字,代表进制,对应进制字符串
二进制:.tostring(2);
八进制:.tostring(8);
十进制:.tostring(10);
十六进制:.tostring(16);
2、string()可以将null和undefined转换为字符串,但是没法转进制字符串
例如将null转换为字符串
<script> var str = string(null); console.log(str, typeof str); </script>
返回的结果为 null,string
将undefined转换为字符串
<script> var str = string(undefined); console.log(str, typeof str); </script>
返回的结果为 undefined,string
该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录 Product