JavaScript的类型检测

来源:互联网 发布:依云软件官网 编辑:程序博客网 时间:2024/06/06 00:34
  • typeof
  • instanceof
  • Object.prototype.toString
  • constructor
  • duck type

typeof
返回字符串,适合函数对象和基本类型的判断。遇到null失效(因为会返回Object),所以判断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"//为什么null是“object”?↑历史原因

instanceof
基于原型链判断的操作符,常用于判断对象类型,适合自定义对象,也可以检测原生对象。
obj instanceof Object
若obj是基本类型,则会返回false
Object是函数对象或函数构造器,若不是,则会抛出typeError异常

[1,2] instanceof Array === truenew Object() instanceof Array === false

不同window或iframe间的对象类型检测不能使用instanceof,因为对象是判断引用

Object.prototype.toString

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 Undefined]";

注意:IE6/7/8中,Object.prototype.toString.apply(null或undefined); === "object Object]";

0 0
原创粉丝点击