js 数据类型判断

/*
    类型
      基本类型   String Number boolean null undefined
      引用类型(对象类型)   Function(特殊的对象 可被执行) Object   Array(特殊的对象 内部是有序的)
    
    判断方法
      typeof 返回对应类型的字符串 小写  
         可以判断 string number undefine boolean function
         不能判断 null 和object  输出为object
         不能判断 object 和 array 输出为object




      instanceof   是否属于谁的实例  instanceof  检测的是原型,内部机制是通过判断对象的原型链中是否有类型的原型。
        Array Function Object都隶属于Object 但也等于自身的类型 

      ===   严等于   可判断唯一值的类型  null undefined

      Object.prototype.toString()

        toString()是Object的原型方法,调用该方法,默认返回当前对象的[[Class]]。这是一个内部属性,其格式为[object Xxx],其中Xxx就是对象的类型。
        对于Object对象,直接调用toString()就能返回[object Object],而对于其他对象,则需要通过call、apply来调用才能返回正确的类型信息。


        Object.prototype.toString.call([])   [object array]


        封装方法
        
    function getType(obj) {
      let type = typeof obj
      if (type !== 'object') {
        return type
      }
      return Object.prototype.toString.call(obj).replace(/^\[object (\S+)\]$/, '$1')
    }
    console.log(getType([]))

     
    */




    var a = null, b = undefined, c = {}, d = [], e = function () { }, f = 'ck', g = 123, h = true
    console.log(a === null)   // true
    console.log(b === undefined)  // true
    console.log(typeof a)   // 'object'
    console.log(typeof b)  // 'undefined'
    console.log(typeof c)   // 'object'
    console.log(typeof d)   // 'object'
    console.log(typeof e)  // 'function'
    console.log(typeof f)   // 'string'  返回对应类型的字符串
    console.log(typeof f === String)   // false   
    console.log(typeof g)   // 'number'
    console.log(typeof h)   //  'boolean'

    console.log(c instanceof Object)   // true
    console.log(d instanceof Object)   // true
    console.log(d instanceof Array)   // true
    console.log(e instanceof Object)   // true
    console.log(e instanceof Function)   // true
    console.log(d instanceof Function)   // false
    console.log(e instanceof Array)   // false

参考链接  https://www.cnblogs.com/crackedlove/p/10331317.html  

以上只是我个人认识,有问题欢迎提出

每天进步一点点  哪怕很慢

posted @ 2020-08-06 09:51  酒北  阅读(67)  评论(0编辑  收藏  举报