标签:
JavaScript提供三种方式判断对象的类型;
一、typeof
typeof 运算符判断对象或数据的类型,返回值为小写的字符串类型;
二、constructor
除了null、undefined之外,对象都具有constructor属性。可以通过此属性判断类型,返回值为首字母大写的对象。
| 对象或数据 | typeof | constructor |
| 12 | number | :SyntaxError |
| false | boolean | Boolean |
| "asdfa" | string | String |
| null | object | :TypeError |
| undefined | undefined | :TypeError |
| NaN | number | Number |
| function(){} | function | Function |
| [1,2] | object | Array |
| new Object() | object | Object |
| {} | object | Object |
| new Number(12) | object | Number |
| new Boolean(false) | object | Boolean |
| new String("asdfad") | object | String |
| Number(12) | number | Number |
| Boolean(false) | boolean | Boolean |
| String("ssss") | string | String |
三、instanceof
通过instanceof运行符可以像Java中一样判断对象的类型。instanceof 运行只能用于判断非空的对象类型
[] instanceof Array; // true {} instanceof Object; // true function Obj(){} new Obj() instanceof Obj; // true 12 instanceof Number; // false new Number(12) instanceof Number; // true false instanceof Boolean; // false new Boolean(false) instanceof Boolean; // true "" instanceof String; // false new String("") instanceof String; // true null instanceof Object; // false
标签:
原文地址:http://www.cnblogs.com/wangg-mail/p/4354763.html