javascript判断数据类型
整理一下javascript判断数据类型的函数
方法一:
1 function isNumber(obj) { 2 return Object.prototype.toString.call(obj) === "[object Number]"; 3 } 4 function isString(obj) { 5 return Object.prototype.toString.call(obj) === "[object String]"; 6 } 7 function isBoolen(obj) { 8 return Object.prototype.toString.call(obj) === "[object Boolen]"; 9 } 10 function isFunction(obj) { 11 return Object.prototype.toString.call(obj) === "[object Function]"; 12 } 13 function isArray(obj) { 14 try { 15 Array.prototype.toString.call(obj); 16 return true; 17 } catch(e) {} 18 return false; 19 } 20 function isNaN(obj) { 21 return obj !== obj; 22 } 23 function isNull(obj) { 24 return obj === obj; 25 } 26 function isUndefined(obj) { 27 return obj === void 0; 28 }
方法二:
1 var class2type = { 2 "[object HTMLDocument]": "Document", 3 "[object HTMLCollection]": "NodeList", 4 "[Object StaticNodeList]": "NodeList", 5 "[obejct IXMLDOMNodeList]": "NodeList", 6 "[object DOMWindow]": "Window", 7 "[object global]": "window", 8 "null": "Null", 9 "NaN": "NaN", 10 "undefined": "Undefined" 11 }, 12 toString = class2type.toString; 13 "Boolean,Number.String,Function.Array.Date,RegExp,Window,Document,Arguments,NodeList".replace(/\w+/g, function(name) { 14 class2type[ "[object " + name + "]" ] = name; 15 }); 16 17 type = function(obj, str) { 18 var result = class2type[ (obj == null || obj !== obj) ? obj : toString.call(obj) ] || obj.nodeName || "#"; 19 if (result.charAt(0) === "#") { //兼容旧版本浏览器与处理个别情况,如window.opera 20 //利用IE6、IE7、IE8 window == document 为true,document == window竟然为false的神奇特性 21 if (obj == obj.document && obj.document != obj ) { 22 result = 'Window'; //返回构造器名字 23 } else if (obj.nodeType === 9) { 24 result = 'Document'; //返回构造器名字 25 } else if (obj.callee) { 26 result = 'Arguments'; //返回构造器名字 27 } else if (isFinite(obj.length) && obj.item) { 28 result = 'NodeList'; //处理节点集合 29 } else { 30 result = toString.call(obj).slice(8, -1); 31 } 32 } 33 if (str) { 34 return str === result; 35 } 36 return result; 37 }

浙公网安备 33010602011771号