JS里的数据类型转换

JS中的七种数据类型:Number、String、Boolean、Symbol、null、undefined、Object


1.其他类型转成Number类型

1.1 Number()方法
Number('1')  //String
//1  
Number('hello')  //String
//NaN 
Number(true)  //Boolean
//1
Number(false)  //Boolean
//0
var a=Symbol()  //Symbol
Number(a)
//VM501:1 Uncaught TypeError: Cannot convert a Symbol value to a number
   // at Number ()
   // at :1:1
Number(null)  //null
//0
Number(undefined)  //undefined
//NaN
var a ={hello: 1,world: 2,length: 2}  //Object
Number(a)
//NaN
1.2 parseInt()方法
将字符串转换成Number类型
parseInt('1',10)  //逗号左侧为字符串,右侧为进制
//1
parseInt('1.1')  //只会转换整型
//1
parseInt('0.1')
//0
parseInt('2a',10)  //此时只会将 数字转换为Number型,后结束
//2
parseInt('99',16)  //将16进制数转换成Numbe型
//153
parseInt('a2') 
//NaN
parseInt(null)
//NaN
parseInt(undefined)
//NaN
1.3 parseFloat()方法
parseFloat('1.1')
//1.1
parseFloat('1')
//1
parseFloat('1.23b')
//1.23
parseFloat('parse')
//NaN
parseFloat('a1')
//NaN
1.4 ''-0
'1'-0
//1
null-0
//0
true-0
//1
false-0
//0
1.5 +''
+'1'
//1
+null
//0
+true
//1
+false
//0


2.其他类型转成String类型

2.1 x.toString()
var a = 1  //Number
a.toString()
"1"
true.toString()  //Boolean
//"true"
false.toString()
//"false"
var a = Symbol()  //Symbol
typeof(a)
//"symbol"
a.toString()
//"Symbol()"
null.toString()  //null
//VM1919:1 Uncaught TypeError: Cannot read property 'toString' of null//
  //  at :1:6
var a = undefined  //undefined
undefined
a.toString()
//VM1988:1 Uncaught TypeError: Cannot read property 'toString' of undefined
 //   at :1:3
var a ={};  //Object
a.toString()
//"[object Object]"
var a = function(){}
undefined
a.toString()
//"function(){}"
2.2 x+""
1+''  //Number
//"1"
true+''  //Boolean
//"true"
false+''
//"false"
var a = Symbol()  //Symbol
a+''
//VM2186:1 Uncaught TypeError: Cannot convert a Symbol value to a string
//    at :1:2
//(anonymous) @ VM2186:1
null+''  //null
//"null"
undefined+''  //undefined
//"undefined"
var a ={}  //Object
a+''
//"[object Object]"
var a =function(){}
a+''
//"function(){}"
2.3 window.String(x)
String(1)  //Number
//"1"
String(true)  //Boolean
//"true"
String(false)
//"false"
String(Symbol())   //Symbol
//"Symbol()"
var a =Symbol()
String(a)
//"Symbol()"
String(null)  //null
//"null"
String(undefined)  //undefined
//"undefined"
var a ={}  //Object
String(a)
//"[object Object]"
var a = function(){}
String(a)
//"function(){}"


3.其他类型转成Boolean类型(5个falsy值,number:0 and NaN;String:'';null;undefined)

3.1 Boolean(x)
Boolean(1)  //Number
//true
Boolean(1.1)
//true
Boolean(-1)
//true
Boolean(0)
//false
Boolean(NaN)
//false
Boolean('1')  //String
//true
Boolean('how')
//true
Boolean('')
//false
Boolean(null)  //null
//false
Boolean(undefined)  //undefined
//false
Boolean([])  //Object
//true
Boolean({})
//true
3.2 !!x
!!1  //Number
//true
!!NaN
//false
!!0
//false
!!'1'  //String
//true
!!''
//false
!!null   //null
//false
!!undefined  //undefined
//false
!![]    //Object
//true

你可能感兴趣的:(JS里的数据类型转换)