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 。欢迎大家访问!
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 。欢迎大家访问!
相关文章推荐
- js-回调函数
- JavaScript动态广告弹出框
- 使用浏览器命令行编写JavaScript代码
- 谈谈JSON对象和字符串之间的相互转换JSON.stringify(obj)和JSON.parse(string)
- 通过js获取上传的图片信息(临时保存路径,名称,大小)然后通过ajax传递给后端的方法
- JavaScript数据类型与运算符
- js跨域问题及解决方案
- NW.js入门学习
- js常见题目
- JavaScript控制元素CSS
- 经典贪心算法(哈夫曼算法,Dijstra单源最短路径算法,最小费用最大流)
- JSON对象和字符串之间的相互转换JSON.stringify(obj)和JSON.parse(string)
- javascript使用eventutil绑定事件
- JS处理json日期格式化问题
- JS日期格式化之javascript Date format
- 详解JavaScript对Date对象的操作问题(生成一个倒数7天的数组)
- jsp片段
- Ember.js 入门指南——异步路由
- Ext JS 开发
- Net深入实战系列—JSON序列化那点事儿