js 中关于数据类型的判断

1.轻量级typeof

typeof 通常能判断以下6种数据类型,在平时开发中使用率比较高,存在的缺点是不够精准。比如typeof 对 array ,null,{}的判断均输出了Object。

  • "number"
  • "string"
  • "boolean"
  • "object"
  • "function"
  • "undefined"  

2.我们来讨论下另一个种方式:Object.prototype.toString.call,这是对象的一个原生原型扩展函数,用来更精确的区分数据类型。

  var   getType=Object.prototype.toString;

  getType.call('aaaa')        输出      [object String]

      getType.call(2222)         输出      [object Number]

      getType.call(true)          输出      [object Boolean]

      getType.call(undefined)  输出      [object Undefined]

      getType.call(null)                  输出   [object Null]

      getType.call({})                   输出   [object Object]

      getType.call([])                    输出   [object Array]
      getType.call(function(){})     输出   [object Function]

还有[object Document](IE)或者  [object HTMLDocument](firefox,google)等dom节点的判断

原文地址:https://www.cnblogs.com/worldforest/p/6824140.html