2010-05-12 20 views
0

我需要檢查JavaScript中的變量類型。我知道3種方式來做到這一點:哪個是檢查變量類型JavaScript的最準確的方法?

  1. instanceof運算符:if(a instanceof Function)

  2. typeof操作:if(typeof a=="function"

  3. toString方法(jQuery使用此):Object.prototype.toString.call(a) == "[object Function]"

哪是在這些解決方案之間進行類型檢查的最準確的方法嗎?爲什麼?請不要告訴我,最後的解決方案只是因爲jQuery使用它才更好。

+0

http://stackoverflow.com/questions/899574/which-is-best-to-use-typeof-or-instanceof – cletus 2010-05-12 08:06:01

+0

我不是在尋找不同的差不多重複的,我知道他們是如何表現。我想知道這是他們之間最安全的解決方案,爲什麼 – mck89 2010-05-12 08:07:53

+0

安全?你的意思是準確的嗎? – kennytm 2010-05-12 08:08:23

回答

1

我的家釀功能,以確定變量「類型」?它也可以決定自定義對象的類型:基於變量,你也可以做的constructor屬性

function whatType(somevar){ 
    return String(somevar.constructor) 
      .split(/\({1}/)[0] 
      .replace(/^\n/,'').substr(9); 
} 
var num = 43 
    ,str = 'some string' 
    ,obj = {} 
    ,bool = false 
    ,customObj = new (function SomeObj(){return true;})(); 

alert(whatType(num)); //=>Number 
alert(whatType(str)); //=>String 
alert(whatType(obj)); //=>Object 
alert(whatType(bool)); //=>Boolean 
alert(whatType(customObj)); //=>SomeObj 

function isType(variable,type){ 
if ((typeof variable).match(/undefined|null/i) || 
     (type === Number && isNaN(variable))){ 
     return variable 
    } 
    return variable.constructor === type; 
} 
/** 
* note: if 'variable' is null, undefined or NaN, isType returns 
* the variable (so: null, undefined or NaN) 
*/ 

alert(isType(num,Number); //=>true 

現在alert(isType(customObj,SomeObj)返回false。但是如果SomeObj是一個普通的構造函數,它將返回true。

function SomeObj(){return true}; 
var customObj = new SomeObj; 
alert(isType(customObj,SomeObj); //=>true 
+0

你確定這適用於所有瀏覽器嗎? – 2010-05-12 09:36:37

+0

據我測試(A級瀏覽器):是的。 – KooiInc 2010-05-12 09:43:44

相關問題