typeof、类型转换

1、typeof

  typeof两种写法:typeof  num;typeof(num)

  typeof(111)       // "number"

  typeof(undefined)    // "undefined"

  typeof('aaaa')           // "string"

  typeof(true)              // "boolean"

  typeof(null)              // "object"

  typeof([1,2,3])          // "array"

  typeof({age:18})       // "object"

  typeof(function  fun(){})  // "function"

2、类型转换

  显式类型转换

  (1)Number(mix)

    Number('111')  // 111

    Number(true)  // 1

    Number(false)  // 0

    Number(null)  // 0

    Number('')  // 0

    Number('   ')  // 0

    Number( )  // 0

    Number(undefined)  // NaN

    Number('abc')  // NaN

    Number('-111')  // -111

  (2)parseInt(string, radix)、parseFloat(string)

    parseInt(string, radix):将字符串转成数字,如果不是字符串,会先将其转成字符串;第二个参数表示将对应进制的数转成十进制

    parseInt(111)  // 1

    parseInt(true)  // NaN

    parseInt(false)  // NaN

    parseInt(null)  // NaN

    parseInt('123')  // 123

    parseInt('123.9')  // 123

    parseInt('abc')  // NaN

    parseInt('')  // NaN

    parseInt('+123.9')  // 123

    parseInt('-123.9')  // -123

    parseInt('10', 2)  // 2

    parseInt('12abc')  // 12

    parseFloat(123.45)  // 123.45

    parseFloat(123)  // 123

    parseFloat('123.4sdf')  // 123.4

  (3)String(mix)

    String(111)  // '111'

    String(true)  // 'true'

    String(NaN)  // 'NaN'

    String(undefined)  // 'undefined'

    String(null)  // 'null'

 

  (4)Boolean(mix)

    Boolean('')  // false

    Boolean(' ')  // true

    Boolean('123')  // true

  (5)toString(radix)

    undefined和null不能用toString方法,否则会报错

    (111).toString()  // '111'

    (2).toString(2)  // '10'

 

  隐式类型转换

  (1)isNaN()

    内部通过Number()方法进行转换,然后和NaN比较

    isNaN(NaN)  // true

    isNaN(123)  // false

    isNaN(undefined)  // false

    isNaN('abc')  // true

  (2)++、--、+(正号)、-(负号)

    在运算前内部调用Number( )方法

    var  a  =  '123';

    a ++;

    console.log(a)  // 124

    +  '456'  // 456

    -  '456'  // -456

  (3)+(加号)

    当加号两边只要有一侧是字符串,就会调用String( )方法

    var  a  =  'b'  +  2;  // b2

  (4)-、*、/、%

    运算符两边调用Number( )方法

    var  a  =  '2'  *  3;  // 6

    var  b  =  'a'  -  4;  // NaN

  (5)==、!=

    1 == '1'  // true

    1  !=  '1'  // false

    undefined  == 0  // false

    undefined  > 0  // false

    undefined  < 0  // false

    null  > 0  // false

    null  < 0  // false

    null  == 0  // false

    undefined  == null  // true

    NaN  ==  NaN  // false

    NaN  !=  NaN  // true

原文地址:https://www.cnblogs.com/cuishuangshuang/p/13228137.html