JavaScript类型检测

来源:互联网 发布:中央日报网络报 编辑:程序博客网 时间:2024/05/22 03:48

类型检测方法如下:typeof,instanceof,Object.prototype.toString,constructor,duck type.


1.部分示例如下:

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


注意:typeof null === "object";


2.  obj instanceof Object

示例:

[1,2] instanceof Array === true;

new Object() instance Array === false;


类型检测小结:

(1)适合基本类型及function检测,遇到null失效;

(2)[[Class]]:  通过{}.toString拿到,适合内置对象和基元类型,遇到null和undefined失效(IE678返回[object Object]).

(3)instanceof:适合自定义对象,也可以用来检测原生对象,在不同iframe和window间检测时失效。


github主页:https://github.com/chenyufeng1991  。欢迎大家访问!


1 0