2013-07-09 59 views
-3
var a; 
typeof(a); 
//undefined 

typeof(c); 
//undefined 

if(c) {} 
//throw error 

我怎麼能知道c不無trycatch存在。明顯的重複後我如何檢查變量是否存在與否

更新:
typeof initializedVariabletypeof notInitializedVariable都將顯示 '未定義'。我的問題是要知道變量是否存在(初始化)。

+0

'if(c!== undefined)'? – Brewal

+2

其他類似問題的問題是什麼(請參見右邊列表,在提問時你應該看到它)? –

+0

如果您嘗試使用不存在的變量,爲什麼不需要警告? – 1983

回答

3

您可以使用typeof運算符。

if (typeof a === 'undefined') { 
    // variable is undefined 
} 
+0

這並沒有解決這個問題(儘管這是一個糟糕的問題)。 – 1983

+0

'typeof c ==='undefined''也是'true'。 – vusan

相關問題