JavaScript基础(一)-- 数据类型转换
1.转数值
方法一:Number(val)
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
231.字符串转数值 1> var a = ''/* 空字符串 */ const b = Number(a) console.log(b ,typeof(b)) 结果:0 number 2> var a = '123456'/* 字符串 */ const b = Number(a) console.log(b ,typeof(b)) 结果:123456 number 2.Boolean转数值 1> var a = true const b = Number(a) console.log(b ,typeof(b)) 结果:1 number 2> var a = false const b = Number(a) console.log(b ,typeof(b)) 结果:0 number 3.null转数值 var a = null const b = Number(a) console.log(b ,typeof(b)) 结果:0 number 4.undefined转数值 var a = undefined const b = Number(a) console.log(b ,typeof(b)) 结果:NaN number
方法二:parseInt([val],[进制默认十进制,高于36结果NaN])
ps:只显示小数点之前的数值
复制代码
1
2
3
4var a = '110.102' const b = parseInt([a],[2]) console.log(b ,typeof(b)) 结果:6 number
方法三:parseFloat (val)
复制代码
1
2
3
4var a = '110.102' const b = parseFloat(a) console.log(b ,typeof(b)) 结果:110.102 number
2.转字符串
string(val)和tostring(val)都可以转化字符串,但是区别是**string方法可以转换任何数据类型包括null,underfunded。tostring可以对参数进行进制转换。最终输出结果还是字符串 **
3.转布尔值
Boolean()其中0,NaN,‘ ’,underfunded,null转换为false,其他都为true。
最后
以上就是跳跃外套最近收集整理的关于JavaScript基础(二)-- 数据类型转换JavaScript基础(一)-- 数据类型转换的全部内容,更多相关JavaScript基础(二)--内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复