【1】定义和零没有toString()方法
undefined.toString();//错误null.toString();//错误
,
【2】布尔型数据真和假返回对应的“真”和“假”
true.toString();//罢嬲?false.toString();//凹?Boolean.toString ();//癴unction 布尔(),{,[native 代码]}”
,
' 1 ' .toString ();//' 1 " .toString ();//薄癮bc”.toString ();//癮bc 'String.toString ();//癴unction 字符串(),{,[native 代码]}”
,
Number.toString ();//癴unction 数量(),{,[native 代码]}”
1.23.toString ();//1.23 'nan.tostring();//澳?Infinity.toString ();//啊蕖?Infinity.toString ();//啊蕖?/pre>2,负浮点数或加“+”号的正浮点数直接跟上.toString (), toString()无效并返回原数值
+ 1.23.toString ();//1.23 typeof + 1.23.toString();//笆俊?.23.toString ();//-1.23 typeof 1.23.toString();//笆俊?/pre>3,整数直接跟上.toString()形式,会报错,提示无效标记,因为整数后的点会被识别为小数点
0. toString ();//Uncaught SyntaxError:, Invalid 或是unexpected 标记因此,为了避免以上无效及报错的情况,数字在使用toString()方法时,加括号可解决
<>前(0).toString ();//' 0 ' (0) .toString ();//?”(+ 1.2) .toString ();//?.2“(-1.2) .toString();//?1.2”(南).toString ();//癗aN”此外,数字类型的toString()方法可以接收表示转换基数(基数)的可选参数,如果不指定此参数,转换规则将是基于十进制。同样,也可以将数字转换为其他进制数(范围在转动)
var n =, 17; n.toString ();//17 'n.tostring (2);//?0001 'n.tostring (8);//' 21 'n.tostring (10);//17 'n.tostring (12);//' 15 'n.tostring (16);//?1”
,
【5】对象对象类型及自定义对象类型加括号返回(对象对象)
{} .toString();//报错,Unexpected token 。({}) .toString ();//[object 对象]({:123}).toString ();//[object 对象]Object.toString ();//癴unction 对象(),{,[native 代码]}”function 人(){,,,this.name =,“测试”; }var person1 =, new 人(); person1.toString ();//癧object 对象]”<强>类型识别强>
console.log (Object.prototype.toString.call (jerry));//[object 字符串]console.log (Object.prototype.toString.call (12));//[object 数字]console.log (Object.prototype.toString.call(真));//[object 布尔]console.log (Object.prototype.toString.call(定义));//[object 定义]console.log (Object.prototype.toString.call (null));//[object null] console.log (Object.prototype.toString.call ({name:,“杰瑞”}));//[object 对象]console.log (Object.prototype.toString.call(函数(){}));//[object 功能]console.log (Object.prototype.toString.call ([]));//[object 数组)console.log (Object.prototype.toString.call (new 日期));//[object 日期]console.log (Object.prototype.toString.call (\ d/));//[object RegExp] function 人(){}; console.log (Object.prototype.toString.call (new 人));//[object 对象]
function 类型(obj) {,,, return Object.prototype.toString.call (obj) .slice (8, 1) .toLowerCase (); } console.log(类型(“杰瑞”));//白址眂onsole.log(式(12));//number console.log(类型(真正的));//安级眂onsole.log(类型(定义));//岸ㄒ濉眂onsole.log(类型(null));//傲恪眂onsole.log(类型({name:,“杰瑞”}));//岸韵蟆眂onsole.log(类型(功能(){}));//肮δ堋眂onsole.log(类型([]));//笆椤眂onsole.log(类型(new 日期));//叭掌凇眂onsole.log(类型(\ d/));//罢虮泶锸健眆unction 人(){}; console.log(类型(new 人));//岸韵蟆?/pre>
,
【6】函数函数类型返回函数代码
当我们对一个自定义函数调用toString()方法时,可以得到该函数的源代码,如果对内置函数使用toString()方法时,会得到一个“(本机代码)”字符串。因此,可以使用toString()方法来区分自定义函数和内置函数
function 测试(){ ,,,提醒(1);//测试} test.toString ();/*”function 测试(){ ,,,,,,,,,,,,,,,,,,,提醒(1);//测试 nulltoString()方法