您的位置:首页 > Web前端 > JavaScript

JavaScript类型检测

2015-10-01 11:50 483 查看
类型检测方法如下: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  。欢迎大家访问!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: