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

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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: