2011-08-18 78 views
9

比較「undefined」值的最佳方法是什麼?

var a; 
(a == undefined) 
(a === undefined) 
((typeof a) == "undefined") 
((typeof a) === "undefined") 

一個,我們應該使用哪有何區別?

+0

http://stackoverflow.com/q/2703102/469210似乎與這一問題有關。 – borrible

+1

可能重複的[Javascript:undefined!== undefined?](http://stackoverflow.com/questions/776950/javascript-undefined-undefined) –

回答

11

諷刺的是,undefined在JavaScript被重新定義,而不是任何人在他們的腦子會做到這一點,例如:

undefined = "LOL!"; 

此時對undefined所有未來的平等檢查將一代產量意想不到的效果!

至於=====(平等運營商)之間的差額,==將試圖從一種類型的值強制轉換到另一個,在英語這意味着0 == "0"將評估爲真實的,即使類型不同(編號VS字符串) - 開發人員傾向於避免這種類型的鬆散相等,因爲這會導致難以調試代碼中的錯誤。

因此,它是最安全的使用方法:

"undefined" === typeof a 

當檢查undefinedness :)

+2

({tries undefined = true})誰在......爲什麼...... AAHG!爲什麼會有人?這是EcmaScript的真正失敗。我從來沒有想過這樣做。 – cwallenpoole

+0

按照我的例子,'爲了lolz!' EcmaScript的下一次迭代(代號爲Harmony)將包括對常量的支持,這對我們的理性來說只是一件好事;)http://wiki.ecmascript.org/doku.php?id=harmony%3aconst – JonnyReeves

+0

它是鏈接到你答案的第一部分:http://stackoverflow.com/questions/2703102/typeof-undefined-vs-null/2703131#2703131 – JohnJohnGa

0
var a; 
(a == undefined) //true 
(a === undefined) //true 
((typeof a) == "undefined") //true 
((typeof a) === "undefined") //true 

但是:

var a; 
(a == "undefined") //false 
(a === "undefined") //false 
((typeof a) == undefined) //false 
((typeof a) === undefined) //false 
+0

當然 - 問題是關於差異沒有結果 - – JohnJohnGa

+0

@JohnJohn好,如果他們都產生同樣的東西,沒有「差異」。但我相信最好的選擇是你的第二選擇。 – Neal

-2

如果聲明var a,那麼就不會是未定義任何更多的 - 這將是null代替。我通常使用typeof a == undefined - 它工作正常。這是在這種情況下尤其有用:

function myfunc(myvar) 
{ 
    if(typeof myvar == "undefined") 
    { 
     //the function was called without an argument, simply as myfunc() 
    } 
} 
+0

['typeof'](https://developer.mozilla.org/en/JavaScript/Reference/Operators/Special/typeof)返回一個字符串。 – Shef

+0

如果語句將爲'FALSE' - 'typeof'返回一個字符串值。 – Neal

+0

嗯,我今天在生產系統中使用它 - 它工作得很好。 –

-1

如果是不確定的,那麼

a == undefined 

實際上將拋出一個錯誤。使用

(typeof a) === "undefined" 

取而代之。

+0

爲什麼會出現錯誤? – Neal

+1

Gah,你是對的,我錯過了OP代碼開頭的「var a」。 –

1

我個人喜歡用

[undefined, null].indexOf(variable) > -1 

還檢查空值。

0

你應該使用上面提到的:

"undefined" === typeof a 

但是,如果你有很多的變量來檢查,你的代碼可以在某些時候變得很惡劣,所以你可以考慮使用Java的做法:

try { vvv=xxx; zzz=yyyy; mmm=nnn; ooo=ppp; } 
catch(err){ alert(err.message); } 

顯然alert()不應該用於生產版本,但在調試版本中它非常有用。 應該在舊的瀏覽器,甚至工作就像IE 6:

https://msdn.microsoft.com/library/4yahc5d8%28v=vs.94%29.aspx

相關問題