数据类型的检测方法

javaScript

数据类型检测有且只有以下这四种方法

  • typeof 检测数据类型的逻辑运算符
  • instanceof 检测是否为某个类的实例
  • constructor 检测构造函数
  • Object.prototype.toString.call 检测数据类型的

# typeof 检测数据类型的逻辑运算符

typeof [value] 返回当前值的数据类型=>"数据类型"

  • 返回的结果都是字符串
  • 局限性
    • typeof null => "object"
    • typeof 不能细分对象类型(检测普通对象或者数组对象等都是"object")
   
    let a = typeof typeof typeof [12,23]
     console.log(a) //=>string
     // typeof [12, 23] => "object"
     // typeof "object" => "string"
     // typeof "string" => "string"

# number

  • NaN和谁都不相等, 包括和自己本身也不相等
  • isNaN(value) 检测这个值是否为有效数字,不是有效数字返回true,是有效数字返回false
  • 案例
      let res = parseFloat("left: 200px") //=> NaN
      if(res===200){
          console.log(200)
      }else if(res===NaN){ //NaN!=NaN
          console.log(NaN)
      }else if(typeof res==="number"){ // typeof NaN == "number"
          console.log("number")
      }else{
          console.log("Invalid Number")
      }
    

把其他数据类型转为数字的方法

  • 强转化(基于低层级制转换)Number([value])
    • 一些隐式转换都是基于Number完成的
      • isNaN("12px") 先把其他类型值转化为数字再检测
      • 数学运算 "12px" - "13"
      • 字符串==数字 两个等于比较很多时候也是要把其他值转为数字
      • ...
  • 弱转换 (基于一些额外的方法)parseInt([value]) parseFloat([value])
    • parseInt/parseFloat
      • 处理字符串:从字符串左侧开始查找有效数字字符,遇到非有效数字字符停止查找 => 如果不是字符串先转化为字符串
    • Number
      • 直接调用浏览器最底层的数据类型检测机制来完成
        • true 1 false 0
        • null 0 undfined NaN
        • 字符串中必须保证都是有效数字才会转换为数字, 否则都是NaN
  • 案例
      parseInt("") //=> NaN
      Number("") //=> 0
      isNaN("") //=> //先把""转换为数字(隐式Number) isNaN(0) false
      parseInt(null) //=> parseInt("null") NaN
      Number(null) //=> 0
      isNaN(null) //=> isNaN(0) false 
      parseInt("12px") //=> 12
      Number("12px") //=> NaN
      isNaN("12px") //=> isNaN(NaN) true
      parseFloat("1.6px")+parseInt("1.2px")+typrof parseInt(null) //=> 1.6 + 1 + typeof NaN => 2.6 + "number" => "2.6number"
      isNaN(Number(!!Number(parseInt("0.8")))) //=> false
      typeof !parseInt(null) + !isNaN(null) //=> "boolean" + true = "booleantrue"
      [] == true //=> 都转化为数字 Number([]) Number('') 0!=1 false
      let result = 10 + false + undefind + [] + "tencent" + null + true + {} //=> "NaNTencentnulltrue[object Object]"
    
  • 总结==规律
    • 对象 == 字符串 对象转化为字符串
    • null == undefined
      • 三个等号下不相等,但是和其他任何的值都不相等
    • NaN 和谁都不相等 包括他自己
    • 剩下情况都是转化为数字,再比较
    • ![] 转换为布尔值进行取反(把其他类型转换为布尔类型遵循的规律: 只有 0/NaN/null/undefind/''五个值是false,其余都是true)
    • {}在没有小括号处理优先级的情况下,不认为是数学运算,加上()才算
    • {}出现运算符的后面认为是数学运算
Last Updated: 2021-04-26 14:38:08