2011-06-09 78 views
1

我有以下的javascript代碼:檢查未定義的值不工作?

var currentIds = localStorage.getItem('currentPairsIds'); 

if ((typeof currentIds === "undefined") || 
    (currentIds == null)) 
     $.myNameSpace.currentIDs = new Array(3); 
    else 
     $.myNameSpace.currentIDs = currentIds.Split(','); 

我使用Firebug調試,雖然currentIds沒有得到任何值,它始終執行else聲明。

更新:

我從HTML5存儲獲取此值。

我在做什麼錯?

+0

那麼這必須意味着'currentIds'的值並不真正'undefined'。 – Pointy 2011-06-09 15:56:33

+0

@Pointy:沒有定義。語句'$ .myNameSpace.currentIDs = currentIds.Split(',');'拋出一個異常。 – VansFannel 2011-06-09 15:59:02

+0

是'currentIds''「」未定義「還是未定義? 'typeof「undefined」'是字符串。 – 2011-06-09 15:59:18

回答

6

這是我已經解決了我的問題:

var currentIds = localStorage.getItem('currentPairsIds'); 

if ((currentIds === undefined) || 
    (currentIds == null) || (currentIds == "undefined")) 
     $.myNameSpace.currentIDs = new Array(3); 
    else 
     $.myNameSpace.currentIDs = currentIds.split(','); 

localStorage.getItem('currentPairsIds');返回字符串"undefined"

Split()函數還有另一個錯誤。正確的版本沒有任何大寫字母。

+2

這是錯誤的,'localStorage.getItem()'不返回字符串「undefined」,它返回'null',你只需要'null'檢查,而不是你盲目測試的其他東西。 – 2012-02-27 17:04:07

+2

@JuanMendes,我有一個未定義的,這個語法適用於我的問題。事實上,這是奇怪的'==「未定義的」'引起了我的問題! – 2014-01-28 21:50:00

+6

@DaveA這是因爲您保存了未定義的內容,本地存儲器將其轉換爲「未定義」字符串。將某些內容保存到localStorage時,應該注意不要將其設置爲undefined或null。我總是將它設置爲空字符串,而不是 – 2014-01-29 00:49:30

0

[編輯編輯編輯編輯:P]


currentIds = "undefined" 

意味着

typeof currentIds == "String" 

另請參見,Detecting Undefined,===是沒有必要的字符串比較。

+0

正確的代碼是... – VansFannel 2011-06-09 15:59:35

+0

你的代碼是正確的,你所描述的currentIDs的值似乎並不符合你期望的值,這個問題在別的地方。 – Andrew 2011-06-09 16:01:18

+0

我已經更新了我的問題這一行'var currentIds = localStorage.getItem('currentPairsIds');'這是我獲取'currentIds'的值。 – VansFannel 2011-06-09 16:19:17

0

我認爲你必須檢查undefined==而不是===。 例如:

typeof currentIds == "undefined" 

這將確保該變量確實未定義或不確定。

+2

'=='或'==='在這種情況下沒有區別。 – MooGoo 2011-06-09 16:32:01

+0

這不會改變,typeof返回一個字符串。 – Andrew 2011-06-09 16:33:02

2

我會用一個直接的比較,而不是出了名的古怪「typeof運算」操作:

if ((currentIds === undefined) || (currentIds === null)) { 
    //... 
+0

yes:no-typeof,與沒有引號的'undefined'比較! – 2013-01-23 08:36:31