Ruby's Louvre

每天学习一点点算法

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

统计

判定类型

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

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

如果您觉得此文有帮助,可以打赏点钱给我支付宝1669866773@qq.com ,或扫描二维码

posted on   司徒正美  阅读(3437)  评论(2编辑  收藏  举报

编辑推荐:
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
点击右上角即可分享
微信分享提示