灵心如玉,守一生无惧|

SadicZhou

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

JS基础11-1强制类型转换String

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
82
83
84
85
<!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>
    /**
     * 强制类型转换:
     * 指将一个数据类型强制转换为其他数据类型
     * 主要是指将其他数据类型转换成:String,Number,Boolean类型
     * **/
    /*
       将其他类型转换为String
       方式一:调用被转换数据类型的toSting()方法
               该方法不会影响原变量,会将转换的结果返回。
               但是要注意null和undefined没有toString()方法,如果调用他们的方法会报错
        方式二:调用String()函数
                并将被转的数据作为参数传递给String()函数
                该方法不会影响原变量,会将转换的结果返回。
                使用String()函数做类型转换时:
                对于Number和Boolean类型来说实际上就是调用了toString()方法
                但是对于null和undefined就不会调用toString(),会将null直接转换为“null”将undefined直接转换为“undefined”
        方式三:使用+拼接一个空字符串''
    */
    const a = 123
    const b = a.toString()//定义变量接收
    //a = a.toString()//用原变量接收
    const c = true
    const d = c.toString()
    // var e = null
    // e = e.toString()
    // var f = undefined
    // f = f.toString()
    console.log(typeof (a))
    console.log(a)
    console.log(typeof (b))
    console.log(b)
    console.log(typeof (d))
    console.log(d)
    // console.log(typeof (e))
    // console.log(e)
    // console.log(typeof (f))
    // console.log(f)
 
    /*
    调用String函数
     */
    const a2 = 123
    const b2 = String(a2)//定义变量接收
    console.log(typeof (b2), b2)
    const c2 = true
    const d2 = String(c2)
    console.log(typeof (d2), d2)
    var e2 = null
    e2 = String(e2)
    console.log(typeof (e2), e2)
    var f2 = undefined
    f2 = String(f2)
    console.log(typeof (f2), f2)
 
    /* 使用+拼接一个空字符串'' */
    const a3 = 123
    const b3 = a3 + ''//定义变量接收
    console.log(typeof (b3), b3)
    const c3 = true
    const d3 = c3 + ''
    console.log(typeof (d3), d3)
    var e3 = null
    e3 = e3 +''
    console.log(typeof (e3), e3)
    var f3 = undefined
    f3 = f3 + ''
    console.log(typeof (f3), f3)
 
</script>
 
</html>

  

本文作者:SadicZhou

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

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

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