JS基础&强制类型转换&String&Number&Boolean


1、强制类型转换

1.1 String

  <script >
    /*
        方式一:
            调用被转换数据类型的tostring()方法,该方法不会影响变量
             a.toString();
            注意:不能对Null、undefined转换
        方式二:
            调用Strin()函数,补兵将被转换的数据作为参数传递
             String(a);
            可以对Null、undefined转换
            对于Number和Boolean实际上就是调用的toString()方法
            对Null、undefined转换
    */
    var a = 123;
    a = a.toString();

    a = true;
    a=a.toString();
    console.log(typeof a);
    console.log(a);

    a = 123;
    a = String(a);
  
    </script>

1.2 Number

<script >
    /*
        方式一:
            使用Number()函数,与String()函数用法一样
             字符串->数字
               1.全部为数字的字符串,直接为数字
               2.有非数字的内容,undefined,转为NaN
               3.空串货空白串,null,转为0
               4.true转为1,false转为0
        方式二:
            专门用来对付字符串
            parseInt();把一个字符串转换为一个整数。将字符串中的有效整数取出
            parseFloat();把一个字符串转为一个浮点数。带有小数的

            对非String使用parseInt或 parseFloat()
                先将其转化为String然后再操作
    */
    var a = "123";
    a = Number(a);
    var b = "123px";
    b = parseInt(b);
    console.log(typeof a);
    console.log(a);
  
    </script>

1.3 其他进制

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script >
    /*
        在js中,表示16进制的数字,使用0X开头
               表示8进制的数字,使用0开头
            表示2进制的数字,使用0b开头

    */
    var a = 0x10;
    a = 070;
    a = 0b10;
    a = parseInt(a,10);//将a转为10进制
    console.log(typeof a);
    console.log(a);
  
    </script>

1.4 Boolean

<script >
    /*
        使用Boolean()函数
            除了0和NaN,都为true;
            Null和undefined都转化为false;
            对象也会转化为true

    */
    var a = 12;
    a = Boolean(a);
    console.log(typeof a);
    console.log(a);
    </script>

猜你喜欢

转载自blog.csdn.net/buxiangquaa/article/details/113605556