JavaScript中共有7種數(shù)據(jù)類型熊杨,本文將介紹以下幾種數(shù)據(jù)類型相互轉(zhuǎn)換的方法。
任意類型轉(zhuǎn)字符串
String(x)
String(1)
>>"1"
String(true)
>>"true"
String(null)
>>"null"
String(undefined)
>>"undefined"
String({})
>>"[object Object]"
x.tostring
(1).toString()
>>"1"
true.toString()
>>"true"
null.toString()
>>Uncaught TypeError: Cannot read property 'toString' of null at <anonymous>:1:6
undefined.toString()
>>Uncaught TypeError: Cannot read property 'toString' of undefined at <anonymous>:1:11
({}).toString()
>>"[object Object]"
x + ''
1+''
>>"1"
true+''
>>"true"
null+''
>>"null"
undefined+''
>>"undefined"
{}+''
>>0
({})+''
>>"[object Object]"
任意類型轉(zhuǎn)數(shù)字
Number(x)
Number('11')
>>11
Number(null)
>>0
Number(undefined)
>>NaN
Number({})
>>NaN
parseInt(x, 10)
parseInt('1111',2)
>>15
parseInt('1111',8)
>>585
parseInt('1111',10)
>>1111
parseInt('1111',16)
>>4369
parseInt('1111fgsfgtr',10)
>>1111
parseInt('true',10)
>>NaN
parseInt(`1111e-2`,10)
>>11
parseFloat(x)
parseFloat(`11`)
>>11
parseFloat(`11.44`)
>>11.44
parseFloat(`11e-2`)
>>0.11
parseFloat(11dfsag)
>>Uncaught SyntaxError: Invalid or unexpected token
parseFloat('11dfsag')
>>11
x - 0
1-0
>>1
'1' - 0
>>1
true - 0
>>1
null - 0
>>0
undefined - 0
>>NaN
({}) - 0
>>NaN
'dfasf' - 0
>>NaN
+x
+1
>>1
+-1
>>-1
+'1'
>>1
+true
>>1
+null
>>0
+undefined
>>NaN
+({})
>>NaN
任意類型轉(zhuǎn)布爾
Boolean(x)
Boolean(null)
>>false
Boolean(undefined)
>>false
Boolean(NaN)
>>false
Boolean('')
>>false
Boolean(0)
>>false
Boolean(false)
>>false
Boolean({})
>>true
!!x
!!null
>>false
!!undefined
>>false
!!NaN
>>false
!!''
>>false
!!0
>>false
!!false
false
!!({})
>>true