当前位置

网站首页> 程序设计 > 开源项目 > 程序开发 > 浏览文章

javascript小技巧之类型判断

作者:小梦 来源: 网络 时间: 2024-06-25 阅读:

类型判断

var class2type = {    "[object HTMLDocument]": "Document",    "[object HTMLCollection]": "NodeList",    "[object StaticNodeList]": "NodeList",    "[object DOMWindow]": "Window",    "[object global]": "Window",    "null": "Null",    "NaN": "NaN",    "undefined": "Undefined"};toString = class2type.toString;var type = function (obj, str) {    var result = class2type[(obj == null || obj !== obj) ? obj : toString.call(obj)] || obj.nodeName || "#";    if (result.charAt(0) === "#") { //兼容旧式浏览器与处理个别情况,如window.opera        //利用IE678 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;};

热点阅读

网友最爱