JavaScript詳細型別判斷
阿新 • • 發佈:2019-02-01
在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());