JS 里的数据类型转换

JS 里的数据类型转换

Js中的数据类型一共有7种,即number,string,boolean,underfine,null,object,symbol

字符串转换

x.toString()
String(x)
' '+ x
1、.toString()

(1).toString()
"1"
true.toString()
"true"

要特别注意null与undefined没有toString的api会报错

null.toString() Uncaught TypeError: Cannot read property 'toString' of null
undefined.toString()Uncaught TypeError: Cannot read property 'toString' of undefined

object会显示"[object Object]"

2、String(x)
这种方法适用于所有数据类型(除object)

String(111) "111"
String(ture)  "ture"
String(null)  "null"
String(undefined)  "undefined"
String({name:'frank'})  "[object Object]"

3、""+x
运算符只能相加相同的数据类型,如果两边的数据类型不同,会优先转换成字符串来相加。

1 + ' '   //"1"
false + ' '  //"false"
null + ' '  //"null"
undefined + ' '  //"undefined"
[1,2,3] + ' ' //"1,2,3"

var obj = {name : 'frank'}
obj + ''  //"[object Object]"

数值转换

Number(x)
parseInt(x,x)
parseFloat(x)
'x' - 0

  • 'x'
    1、Number(x)
Number('123')
123

2、parseInt('123'10)

parseInt(x,x)
123

parseFloat(x)

parseFloat(123)
123

'x' - 0

'123'-0
123
  • 'x'
+'123'
123

布尔转换
Boolean()
!! x

1、Boolean()

Boolean(1)  //true
Boolean({})  //true

2、!! x

!true //false
!!true //true
!!1 //true

五个falsy值,即转换成Boolean后为false的值:
0 、 NaN 、 null 、 undefined 、‘’(空字符串)。

手动大写的内存图!!!
1、


image.png
image.png

2、


image.png
image.png

3、


image.png
image.png

4、


image.png
image.png
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容