js类型检测

类型检测常用三种方法

  1. typeof
  2. instanceof
  3. Object.prototype.toString.apply()

一、typeof

适用于基本类型以及function检测,遇到null失效

typeof 100 //number
typeof true //boolean
typeof function //function
typeof undefined //undefined
typeof new Object() //object
typeof [1,2] //object
typeof NaN //number
typeof null //object

二、instanceof

适合自定义对象,也可用来检测原生对象,在不同的iframe以及window之间检测时失效

[1,2]instanceof Array //true
new Object() instanceof Array //false
new Object() instanceof Object //true
1 instanceof Number //false
"string" instanceof String //false

从上面代码也可以看出基本类型并不能通过instanceof检测

三、Object.prototype.toString.apply()

适合内置对象以及基元类型

Object.prototype.toString.apply(1)
"[object Number]"
Object.prototype.toString.apply([1,2,3,4])
"[object Array]"
Object.prototype.toString.apply(new Object())
"[object Object]"
Object.prototype.toString.apply(function(){})
"[object Function]"
Object.prototype.toString.apply(null)
"[object Null]"
Object.prototype.toString.apply(true)
"[object Boolean]"
Object.prototype.toString.apply(undefined)
"[object Undefined]"
Object.prototype.toString.apply("string")
"[object String]"

这个方法检测类型很酷,是不是!!!

注意:

在IE678中Object.prototype.toString.apply(null)返回的仍是object

其他两种判断方法

自己百度去吧!!!

  1. constructor
  2. duck type
posted @ 2017-05-14 22:35  郑闯  阅读(267)  评论(0编辑  收藏  举报