灵心如玉,守一生无惧|

SadicZhou

园龄:3年2个月粉丝:7关注:4

JS基础11-2强制类型转换Number

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
<!DOCTYPE html>
<html lang="zh-CN">
 
<head>
   <meta charset="UTF-8">
   <meta name="viewport"
      content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0,minimal-ui:ios">
   <meta http-equiv="X-UA-Compatible" content="ie=edge">
   <title>Document</title>
   <link rel="stylesheet" href="">
   <script src=""></script>
</head>
<script>
   /*
      将其他类型转换为Number
      转换方式一:
     使用Number()函数,使用方式与Sting()函数相同
      1.如果是纯数字的字符串,则直接将其转换为数字
      2.如果字符串中有非数字的内容则转换为NAN(NOT A NUMBENR)
      3.如果字符串是空字符串或者是一个全是空格的字符串则转换为0
 
      布尔 --》数字:true转换为1;false转换为0;
      null --》数字:null转为数字是0
      undefined --》数字:undefined转为数字是NAN
      转换方式二:
       这种方式专门用来转换字符串
       paseInt()把一个字符串转换为整数
       paseInt()方法把一个字符串中有效的整数内容取出来转换为了Number,注:遇到第一个不是整数的字符后就会不在往下找
       paseFloat()把一个字符串转换为浮点数
       paseFloat()方法把一个字符串中有效的浮点数内容取出来转换为了Number,注:遇到第一个不是浮点数的字符后就会不在往下找
       如果对非String类型使用parseInt()或者parseFloat()方法
       会先将其转换为String,parseInt()方法来取整
   */
   /*
    使用Number()函数转换
    */
   var a = '123'
   a = Number(a)//123
   console.log(typeof (a), a)
   var b = true
   b = Number(b)//1
   console.log(typeof (b), b)
   var c = null
   c = Number(c)//NAN
   console.log(typeof (c), c)
   var d = undefined
   d = Number(d)//NAN
   console.log(typeof (d), d)
   var e = 'abc'
   e = Number(e)//NAN
   console.log(typeof (e), e)
   var f = '1abc'
   f = Number(f)//NAN
 
   console.log(typeof (f), f)
 
   /*
   使用parseInt()和parseFloat()函数转换
   */
   a2 = '100px'
   a2 = parseInt(a2)//100
   b2 = '-100px'
   b2 = parseInt(b2)//-100
   d2 = 'ab100bc'
   d2 = parseInt(d2)//NAN
   c2 = '100.001px'
   c2 = parseFloat(c2)//100.001
   e2 = '-100.001px'
   e2 = parseFloat(e2)//-100.001
   g = 123.234
   g = parseInt(g)//123
   console.log(typeof (a2), a2)
   console.log(typeof (b2), b2)
   console.log(typeof (c2), c2)
   console.log(typeof (d2), d2)
   console.log(typeof (e2), e2)
   console.log(typeof (g), g)
 
</script>
 
</html>

  

本文作者:SadicZhou

本文链接:https://www.cnblogs.com/SadicZhou/p/16935787.html

版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。

posted @   SadicZhou  阅读(203)  评论(0编辑  收藏  举报
点击右上角即可分享
微信分享提示
评论
收藏
关注
推荐
深色
回顶
收起
  1. 1 尚好的青春 孙燕姿
  2. 2 孙燕姿
  3. 3 克卜勒 孙燕姿
- 孙燕姿
00:00 / 00:00
An audio error has occurred, player will skip forward in 2 seconds.