toString()
false.toString()//"false"
typeof false.toString();//"string"
数值情况下的tostring()
Number.toString();//"function Number() { [native code] }"
1、正浮点数及NaN、Infinity加引号返回
1.23.toString();//'1.23' NaN.toString();//'NaN' Infinity.toString();//'Infinity'
typeof NaN.toString()//string
NaN == typeof NaN.toString()//false
2、负浮点数或加'+'号的正浮点数直接跟上.toString(),相当于先运行toString()方法,再添加正负号,转换为数字
typeof +1.23.toString();//"number"
typeof 1.23.toString();//"string"
3、整数直接跟上.toString()形式,会报错,提示无效标记,因为整数后的点会被识别为小数点,未解决这一类问题 使用括号将整数括起来
对象情况下的tostring()
{}.toString();//报错,Unexpected token . ({}).toString();//[object Object]
typeof ({}).toString();//"string"
({a:123}).toString();//[object Object] Object.toString();//"function Object() { [native code] }"
类型识别
console.log(Object.prototype.toString.call("jerry"));//[object String] console.log(Object.prototype.toString.call(12));//[object Number] console.log(Object.prototype.toString.call(true));//[object Boolean] console.log(Object.prototype.toString.call(undefined));//[object Undefined] console.log(Object.prototype.toString.call(null));//[object Null] console.log(Object.prototype.toString.call({name: "jerry"}));//[object Object] console.log(Object.prototype.toString.call(function(){}));//[object Function] console.log(Object.prototype.toString.call([]));//[object Array] console.log(Object.prototype.toString.call(new Date));//[object Date] console.log(Object.prototype.toString.call(/d/));//[object RegExp]
valueof()
undefined和null没有valueof() 方法
布尔型数据true和false返回原值。布尔型数据的包装对象返回true或false
true.valueOf();//true typeof true.valueOf();//'boolean' false.valueOf();//false typeof false.valueOf();//'boolean' Boolean.valueOf();//Boolean() { [native code] } typeof Boolean.valueOf();//'function'
字符串类型原值返回。字符串类型的包装对象返回字符串值
'1'.valueOf();//'1' ''.valueOf();//'' 'abc'.valueOf();//'abc' String.valueOf();//String() { [native code] } typeof String.valueOf();//'function'
数值情况下的valueof()
1.整数直接跟.valueOf()形式,会报错,提示无效标记,因为整数后的点被识别为小数点,所以尽量加括号
-0的valueOf()值是-0,而-0的toString()值是'0'
2、浮点数原值返回
1.23.valueOf();//1.23
+1.23.valueOf();//1.23
-1.23.valueOf();//-1.23 NaN.valueOf();//NaN Infinity.valueOf();//Infinity -Infinity.valueOf();//-Infinity
typeof -1.23.valueOf()//"number"
对象情况下的valueof()
{}.valueOf();//报错,Unexpected token . ({}).valueOf();//Object{} typeof ({}).valueOf();//'object' ({a:123}).valueOf();//Object{a:123} Object.valueOf();//Object() { [native code] } typeof Object.valueOf();//'function'