js有六大数据类型:String,Number,Boolean,Null,Undefined,Object。其中前五项数据类型被称作原始类型。
typeof 操作符返回值有"string","number","boolean","undefined","object","function"。其中Null类型的返回值是"object",而Function作为Object类型的子类,返回的结果却是"function"
非数值类型转换为数值类型规则
//空字符串被转换为0 console.log(Number(""));//0 //字符串只包含数字,返回十进制数 console.log(Number("19"));//19 //字符串是十六进制形式,返回相等的十进制 console.log(Number("0x19"));//25 //字符串是浮点形式,返回浮点数 console.log(Number("12.5"));//12.5 //字符串是浮点形式,返回浮点数 console.log(Number("1.234e2"));//123.4 //除以上的字符串形式都返回NaN console.log(Number("a")); //NaN //Boolean true 返回1 console.log(Number(true));//1 //Boolean false 返回0 console.log(Number(false));//0 //数字形式,返回原参数 console.log(Number(23));//23 //Null类型返回0 console.log(Number(null));//0 //Undefined类型返回NaN console.log(Number(undefined));//NaN
对象类型转换有特殊的规则
将对象类型强转为Number类型时,先调用对象的valueOf()方法,如果方法的返回值是原始类型,那么就Number(valueOf的返回值),如果方法的返回类型是Object类型,那么会进一步调用对象的toString()方法。toString()方法的返回值如果是原始类型,则Number(toString的返回值),如果toString()方法的返回值是Object类型,那么最终报错了
<script> var obj = { name:"pmx", age:20, valueOf:function(){ console.log("value of"); return this.name; }, toString:function(){ console.log('to string'); return this.name; } } </script>
Number('pmx')的结果为NaN
<script> var obj = { name:"pmx", age:20, valueOf:function(){ console.log("value of"); return null }, toString:function(){ console.log('to string'); return this.name; } } </script>
Number(null)的结果是0
<script> var obj = { name:"pmx", age:20, valueOf:function(){ console.log("value of"); return {} }, toString:function(){ console.log('to string'); return this.name; } } </script>
valueOf()返回的是非原始类型,那么调用obj的toString()方法,Number('pmx')结果为NaN
<script> var obj = { name:"pmx", age:20, valueOf:function(){ console.log("value of"); return {} }, toString:function(){ console.log('to string'); return {}; } } </script>
toString()的返回结果是Object类型,最后Number强制转换失败,报错了
<script> var obj = { name:"pmx", age:20, valueOf:function(){ console.log("value of"); return {} }, toString:function(){ console.log('to string'); return { a:10, valueOf:function(){ return 10; }, toString:function(){ return 'a' } }; } } </script>
toString()方法返回的对象中自定义了valueOf()方法和toString()方法,仍然报错,说明数值强转不会递归进行