jQuery中的型別判斷

2022-02-21 17:35:35 字數 2449 閱讀 4268

在jquery中有乙個type方法,在1.11.2中是這樣寫的

1

var class2type ={};

2var tostring =class2type.tostring;

3 jquery.each("boolean number string function array date regexp object error".split(" "), function

(i, name) );

6 type: function

( obj )

10return

typeof obj === "object" || typeof obj === "function" ?

11 class2type[ tostring.call(obj) ] || "object":

12typeof

obj;

13 }

其核心在於使用array.prototype.tostring.call,因為在任何值上呼叫object原生的tostring()方法,都會返回乙個[object nativeconstructorname]格式的字串。每個類在內部都有乙個[[class]]屬性,這個屬性中就指定了上述字串中的建構函式名。

之所以這樣做是因為js內建的型別檢測機制並非完全的可靠。

例如,typeof null  輸出「object」

typeof alert 在ie8中輸出「object」

typeof 輸出「object」

instanceof如果是跨文件比較的話,就會存在很大的問題。利用constructor屬性的話,在低版本ie中又會出現問題(window.constructor在ie7下為undefined)。而且,二者不方便判斷基本型別。

所以說,判斷是否是函式,陣列就可以這樣寫

1 isfunction: function

( obj ) ,

45 isarray: array.isarray || function

( obj ) ,

奇怪的是判斷是否為window

1 iswindow: function

( obj ) ,

似乎偽裝一下也能騙過去,可能是因為window物件屬於bom,前面的方法對它不管用。

然後是isplainobject,2.0.1中這樣寫。

1 isplainobject: function

( obj ) 910

//support: firefox <20

11//

the try/catch suppresses exceptions thrown when attempting to access

12//

the "constructor" property of certain host objects, ie. |window.location|

13//

14try

19 } catch

( e )

2223

//if the function hasn't returned already, we're confident that

24//

|obj| is a plain object, created by {} or constructed with new object

25return

true

;26 }

這裡的plainobject應該是如{},new object,這樣的物件。

第乙個if可以排除非object物件,dom節點,window。

第二個if是可以排除window.location這樣的bom物件。

其中,class2type = {},

core_hasown = class2type.hasownproperty

因為這些bom物件的建構函式的原型肯定不是object {},自身是沒有isprototypeof這個屬性的。

然後是判斷空物件,也就是沒有可列舉屬性的物件。

1 isemptyobject: function

( obj )

6return

true

;7 }

還有乙個函式是用來判斷是否是數字,

//

1.11.2

isnumeric: function

( obj ) ,

向parsefloat中傳個陣列,如[2,4],返回2,但是陣列參加右邊的運算結果肯定是false,不知道為什麼要先判斷是否是陣列。

這裡如果傳入乙個如'123'、'321'這樣的字串的話也是可以通過的。

在1.8.0和2.0.1版本中直接就是!isnan( parsefloat(obj) ) && isfinite( obj ).

jQuery瀏覽器型別判斷

在專案開發中,經常因為不同的瀏覽器而要進行一些特殊的處理,那麼我們如果判斷不同的瀏覽器的型別呢?下面通過jquery為我們提供的方法進行判斷 function else if browser.safari else if browser.mozilla else if browser.opera e...

jQuery中判斷input的disabled屬性

var val ipt is disabled true false var val ipt prop disabled true false var val ipt attr disabled disabled undefined prop 設定 ipt prop disabled true 禁用...

Scala 中的型別判斷

scala中物件提供isinstanceof和asinstanceof方法。判斷物件是否為指定型別 val trueo lse boolean 物件.isinstanceof 型別 將物件轉換為指定型別 val 變數 物件.asinstanceof 型別 object test01 isinstan...