Ruby's Louvre

每天学习一点点算法

导航

判定类型

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

//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;
	}

posted on 2010-01-20 18:56  司徒正美  阅读(3435)  评论(2编辑  收藏  举报