javascript判断数据类型
2016-02-14 15:18
543 查看
整理一下javascript判断数据类型的函数
方法一:
方法二:
方法一:
function isNumber(obj) { return Object.prototype.toString.call(obj) === "[object Number]"; } function isString(obj) { return Object.prototype.toString.call(obj) === "[object String]"; } function isBoolen(obj) { return Object.prototype.toString.call(obj) === "[object Boolen]"; } function isFunction(obj) { return Object.prototype.toString.call(obj) === "[object Function]"; } function isArray(obj) { try { Array.prototype.toString.call(obj); return true; } catch(e) {} return false; } function isNaN(obj) { return obj !== obj; } function isNull(obj) { return obj === obj; } function isUndefined(obj) { return obj === void 0; }
方法二:
var class2type = { "[object HTMLDocument]": "Document", "[object HTMLCollection]": "NodeList", "[Object StaticNodeList]": "NodeList", "[obejct IXMLDOMNodeList]": "NodeList", "[object DOMWindow]": "Window", "[object global]": "window", "null": "Null", "NaN": "NaN", "undefined": "Undefined" }, toString = class2type.toString; "Boolean,Number.String,Function.Array.Date,RegExp,Window,Document,Arguments,NodeList".replace(/\w+/g, function(name) { class2type[ "[object " + name + "]" ] = name; }); type = function(obj, str) { var result = class2type[ (obj == null || obj !== obj) ? obj : toString.call(obj) ] || obj.nodeName || "#"; if (result.charAt(0) === "#") { //兼容旧版本浏览器与处理个别情况,如window.opera //利用IE6、IE7、IE8 window == document 为true,document == window竟然为false的神奇特性 if (obj == obj.document && obj.document != obj ) { result = 'Window'; //返回构造器名字 } else if (obj.nodeType === 9) { result = 'Document'; //返回构造器名字 } else if (obj.callee) { result = 'Arguments'; //返回构造器名字 } else if (isFinite(obj.length) && obj.item) { result = 'NodeList'; //处理节点集合 } else { result = toString.call(obj).slice(8, -1); } } if (str) { return str === result; } return result; }
相关文章推荐
- 关于js中函数的闭包 深入了解
- js实现继承的方法
- JavaScript内存优化
- JavaScript日期集合(今日,昨日,本周一,周末 ,月初,月末)
- javascript移动设备触屏事件
- JSON 之FastJson解析
- JS:收集的一些Array及String原型对象的扩展实现代码
- JS 替换
- javaScript事件总结
- js中的DOM节点
- js实现当前导航菜单高亮显示
- js 中对象的特性
- 2016.02.14 总结JS事件
- js中的模块化编写思维
- json嵌套json
- JavaScript高级程序设计学习笔记第十三章--事件
- js
- JS图片切换
- Gedit安装Format JSON插件
- JavaScript中通过提示框跳转页面的方法