js类型识别的方法?

typeof a

  • 可以判别标准类型,除了null之外
    typeof 1 返回结果:"number" typeof {} 返回结果:"object"

  • 不能判别具体的对象类型,除了function之外
    typeof [1] 返回结果:"object" typeof function(){} 返回结果:"function"

a instanceof b

  • 可以判别内置对象类型
    [] instanceof Array 返回结果:true new String() instanceof String 返回结果:true

  • 不能判别原始类型值
    'a' instanceof String 返回结果:false

  • 可以判别自定义对象类型

     function Point(x,y){
             this.x = x;
             this.y = y
         }
    
     var c = new Point(1,2)
     c instanceof Point

    返回结果:true

a.constructor

  • 可以判别标准数据类型(undefined和null除外)
    '123'.constructor == String 返回结果:true

  • 可以判别具体的内置对象类型
    [1,2].constructor == Array 返回结果:true

  • 可以判别自定义对象类型

     function Point(x,y){
         this.x = x;
         this.y = y
     }
    
     var c = new Point(1,2)
     c.constructor == Point

    返回结果:true

Object.prototype.toString.call(a)

  • 可以判别标准数据类型
    Object.prototype.toString.call(1)返回结果:"[object Number]" Object.prototype.toString.call(undefined) 返回结果:"[object Undefined]"

  • 可以判别内置对象类型 
    Object.prototype.toString.call([a]) 返回结果:"[object Array]"

  • 不能判别自定义对象类型

  function Point(x,y){
      this.x = x;
      this.y = y
  }
  var c = new Point(1,2)
  Object.prototype.toString.call(c)

返回结果:"[object Object]"

工作中可以写一个函数方便判定

      function type(obj){
          return Object.prototype.toString.call(obj).slice(8,-1)
      }

type('a') 返回结果: "String" type([a]) 返回结果: "Array"

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值