JavaScript详细类型判断

来源:互联网 发布:单片机315m无线模块 编辑:程序博客网 时间:2024/06/08 07:51

JavaScript中,如果要判断一个变量的类型,很多人会使用typeof关键字,看处理后的返回类型。这种方式,只能得到变量的大概类型,而无法获取它的详细信息。

在某些框架,变量类型判断是借助Object.prototype.toString方法,看变量作为this调用该方法的返回结果是怎样的类型。这种方式,在我看来还是不够详细。

我实现了一个type方法,它相对于以上的方式,有如下的补充与改进:

1.对于数字型变量,区分是整型,浮点型,NaN还是正负无穷大。

2.对于字符串型变量,区分是数字还是非数字。

3.对于对象类型,返回其构造函数名。

function type(val) {    var toStr = Object.prototype.toString;        if(val === void 0){        return "Undefined";    }    else if(val === null){        return "Null";    }    else if(typeof val === "boolean"){        return "Boolean";    }    else if(typeof val === "function"){        return "Function";    }    else if(typeof val === "string"){        if(isNaN(val)){            return "String";        }        else{            return "String Numeric";        }    }    else if(toStr.call(val) === "[object Object]" && val.constructor === Object){        return "Object";    }    else if(typeof val === "number"){        if(isNaN(val)){            return "Number NaN";        }        if(!isFinite(val)){            return "Number Infinite";        }        if(parseInt(val) == val){            return "Number Integer";        }        else{            return "Number Float";        }    }    else{        var str = val.constructor.toString();        return str.slice(str.indexOf(" ") + 1 , str.indexOf("("));    }}//'Undefined'type(undefined);//'Null'type(null);//'Boolean'type(true); //'Function'type(function(){});//'Function'type(Math.max);//'String'type('abc'); //'Object'type({snap: "crackle"});//'Number Integer'type(1); //'Number Float'type(1.1); //'Number NaN'type(NaN); //'Number Infinite'type(-Infinity); //'String Numeric'type('123');type('123.321');type('0xF');//'RegExp'type(/abc/);//'Array'type([1,2,3]); function Custom(){}//'Custom'type(new Custom()); 


0 0