標籤:
javascript中,類型判斷是各大類庫的基礎之一。來看看是怎麼實現的。
主要有三種方法:
1,滿是坑的typeof (認識其坑後是一個利器)
typeof 返回6種基本類型:number, string, object, boolean, undefined, function
其中有幾個很容易誤導的:
(1)typeof obj === ‘object‘,你卻不能真正當對象使用
if (typeof obj === ‘object‘) { obj.a() // 這裡報錯}
(2)typeof NAN === ‘number‘,你卻不能使用它進行算術運算
if (typeof num === ‘number‘) { num = num + 10 // 執行後num仍然是NaN}
(3)Safar5,Chrome7之前的版本對正則對象返回 ‘function‘
(4) 不能區分對象、數組、正則,對它們操作都返回‘object‘
2,遺憾的constructor 和 instanceof
為什麼說遺憾,因為在跨文檔操作時候,會產生bug
// 用法function isArray(arr){ return typeof arr == "object" && arr.constructor == Array;}// 跨文檔操作時就呵呵了window.onload=function(){var iframe_arr=new window.frames[0].Array;alert(iframe_arr instanceof Array); // falsealert(iframe_arr.constructor == Array); // false}
3, 最後的解藥:Object.prototype.toString.
直接把jQuery.2.0.3源碼貼上
class2type = {}
core_toString = class2type.toStringjQuery.each("Boolean Number String Function Array Date RegExp Object Error".split(" "), function(i, name) { class2type[ "[object " + name + "]" ] = name.toLowerCase();});type: function( obj ) { if ( obj == null ) { return String( obj ); } // Support: Safari <= 5.1 (functionish RegExp) return typeof obj === "object" || typeof obj === "function" ? class2type[ core_toString.call(obj) ] || "object" : typeof obj; }
總結:除了自訂類型外外,組合類別型基本用Object.prototype.toString這種方法。typeof方法可以用來判斷boolean, undefined, string類型
javascript類型判斷