js类型检测

1、typeof  或者  typeof()  适合基本类型及function检测,遇null失效

ex:  typeof 100      返回值为 "number"

     typeof true  返回值为 "boolean"

     typeof function(){}  返回值为  "function"

     typeof undefined  返回值为  "undefince"

     typeof new Object()  返回值为  "object"

     typeof [1,2]  返回值为  "object"

     typeof NaN  返回值为  "number"

       typeof null  返回值为  "object"

2、instanceof(基于原型链判断)  适合自定义对象,也可用来检测原生对象,在不同iframe和window间检测时失效

  obj  instanceof  Object    #instanceof操作符期望左操作数是一个对象,如果不是,会返回false,期望右操作符实一个函数对象或函数构造器,若不是,会跑出一个type error异常

3、Object.prototype.toString.apply()  适合内置对象和基本类型,遇到null和undefined失效

注意:IE6/7/8 Object.prototype.toString.apply(null) 返回值为  "[object Object]"

Object.prototype.toString.apply([])  返回值为  "[object Array]"

Object.prototype.toString.apply(function(){})  返回值为  "[object Function]"

Object.prototype.toString.apply(null)  返回值为  "[object Null]"

Object.prototype.toString.apply(undefined)  返回值为  "[object Undefinde]"

4、constructor

5、duck type

原文地址:https://www.cnblogs.com/yaohunzhanyue/p/5696877.html