zoukankan      html  css  js  c++  java
  • 判定类型

    目前最精确的判定方法(不包括自定义类型)

    //2010.6.1更新
            var is = function (obj,type) {
            return (type === "Null" && obj === null) ||
            (type === "Undefined" && obj === void 0 ) ||
            (type === "Number" && isFinite(obj)) ||
             Object.prototype.toString.call(obj).slice(8,-1) === type;
        },
    

    用法如下:

    //***************示例一,判定数组与函数
            var forEach = function(array,fn,bind){
              if(is(array,"Array") && is(Array.forEach,"Function")){
                array.forEach(fn,bind);
              }else{
                for(var i=0,n=array.length;i<n;i++){
                  i in array && fn.call(bind,array[i],i,array)
                }
              }
            }
    //***************示例二,判定null
    var a = null
    alert(is(a,"Null"))
    //***************示例二,判定undefined
    var b
    alert(is(b,"Undefined"))
    

    另一个变种,直接返回表示类型的字符串

            var getType = function (obj) {
              var _toString = Object.prototype.toString,undefined;
              return obj === null? "Null":
                obj === undefined ? "Undefined":
                _toString.call(obj).slice(8,-1);
            };
    

    用法:

      var arr = [1,2,3,4]
            alert(getType(arr));//Array
            var nil = null
            alert(getType(nil))//Null
            var und ;
            alert(getType(und))//Undefined
            var spans = document.getElementsByTagName("span");
            alert(getType(spans)) //HTMLCollection
            alert(getType(spans[0].childNodes))//NodeList
    
    
    var _toS = {}.toString, 
        _types = { 
        'undefined' : 'undefined', 
        'number' : 'number', 
        'boolean' : 'boolean', 
        'string' : 'string', 
        '[object Function]' : 'function', 
        '[object RegExp]' : 'regexp', 
        '[object Array]' : 'array', 
        '[object Date]' : 'date', 
        '[object Error]' : 'error' 
    }; 
    function type(o) { 
        return _types[typeof o] || _types[_toS.call(o)] || (o ? 'object' : 'null'); 
    }  
    
    //2010.7.20
    function isA (thing, canon) {
      // special case for null and undefined
      if (thing == null || canon == null) {
        return thing === canon;
      }
      return Object.getPrototypeOf(Object(thing)) == Object.getPrototypeOf(Object(canon));
    }
    function isBool (thing) {
      return isA(thing, true);
    }
    function isNumber (thing) {
      return isA(thing, 0) && isFinite(thing);
    }
    function isString (thing) {
      return isA(thing, "");
    }
    
    //2010.11.2更新
    //用于取得数据的类型(一个参数时)或判定数据的类型(两个参数时)
    // $$$$(type(1,"Number"));
    // $$$$(type(NaN,"NaN"));
    // $$$$(type(void(0),"Undefined"));
    // $$$$(type("aaa","String"));
    // $$$$(type([1,2,3],"Array"));
    // $$$$(type(/i/,"RegExp"));
    // $$$$(type({},"Object"));
    // $$$$(type(document,"Document"));
    // $$$$(type(document.body,"BODY"));
    // $$$$(type(window,"Window"));
    // $$$$(type(true,"Boolean"));
    // $$$$(type(document.getElementsByTagName('p'),"HTMLCollection"));
     var type = (function(){
            var reg = /^(\w)/,
            regFn = function($,$1){
                return $1.toUpperCase()
            },
            to_s = Object.prototype.toString;
            return function(obj,str){
                var result = (typeof obj).replace(reg,regFn);
                if(result === 'Object' || (result === 'Function' && obj.exec) ){//safari chrome中 type /i/ 为function
                    if(obj===null) result = 'Null';
                    else if(obj.window==obj) result = 'Window'; //返回Window的构造器名字
                    else if(obj.callee) result = 'Arguments';
                    else if(obj.nodeType === 9) result = 'Document';
                    else if(obj.nodeName) result = (obj.nodeName+'').replace('#',''); //处理元素节点
                    else if(!obj.constructor || !(obj instanceof Object)){
                        if("send" in obj && "setRequestHeader" in obj){//处理IE5-8的宿主对象与节点集合
                            result = "XMLHttpRequest"
                        }else if("length" in obj && "item" in obj){
                            result = "namedItem" in obj ?  'HTMLCollection' :'NodeList';
                        }else{
                            result = 'Unknown';
                        }
                    }else result = to_s.call(obj).slice(8,-1);
                }
                if(result === "Number" && isNaN(obj))  result = "NaN";
                //safari chrome中 对 HTMLCollection与NodeList的to_s都为 "NodeList",此bug暂时无解
                if(str){
                    return str === result;
                }
                return result;
            }
        })()
    

    再来个精简版

    //2011.7.29
    	function isType (obj, type) {
    		return toString.call(obj).indexOf('[object ' + type) == 0;
    	}
    
  • 相关阅读:
    Silverlight项目笔记1:UI控件与布局、MVVM、数据绑定、await/async、Linq查询、WCF RIA Services、序列化、委托与事件
    斯坦福iOS7公开课1-3笔记及纸牌Demo
    使用CocoaPods管理第三方开源类库
    Mac下安装Django
    iOS与H5界面JSBridge交互Demo
    手动导入swift三方danielgindi/Charts到OC工程中教程
    button自适应宽度 并根据屏幕宽自动换行排列
    ReactNative中iOS和Android的style分开设置教程
    react-native DatePicker日期选择组件的实现
    react-native Simulator com+r不能刷新模拟器
  • 原文地址:https://www.cnblogs.com/rubylouvre/p/1652646.html
Copyright © 2011-2022 走看看