2009-11-13 116 views
8

如果我想檢查變量是否爲空或不存在,那麼mos可靠的方法是什麼?什麼是檢查JavaScript變量是否爲空的最可靠的方法?

有diferent例子:

if (null == yourvar) 

if (typeof yourvar != 'undefined') 

if (undefined != yourvar) 
+2

使用'==='和'!==' – jantimon 2009-11-13 10:28:55

+0

「可靠」是什麼意思? – rjmunro 2009-11-13 11:13:22

+0

**另請參閱:** http://stackoverflow.com/questions/24318654 – dreftymac 2014-06-20 01:46:37

回答

13

以上皆非。

您不想使用==或其各種因爲it performs type coercion。如果您確實想要檢查是否顯式爲空,請使用===運算符。

然後再次,您的問題可能表明您的要求可能有些不明確。您是否確切地指null;還是undefined也算呢? myVar === null一定會告訴你變量是否爲null,這是你問的問題,但這真的是你想要的嗎?

請注意,this SO question中有更多信息。這不是直接重複的,但它涵蓋了非常相似的原則。

+0

空和未定義的類型是==(但不是===)。 – rahul 2009-11-13 10:34:13

+0

https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Operators/Comparison_Operators – rahul 2009-11-13 10:34:47

+0

感謝您的鏈接adamantium,添加到我的答案。 – 2009-11-13 10:37:56

4

我喜歡

if (null == yourvar) 

從而避免了在這種情況下

if (yourvar = null) 

編輯

JavaScript有兩個嚴格和類型轉換相等比較意外分配。對於全等被比較的對象必須具有相同的類型和:

* Two strings are strictly equal when they have the same sequence of characters, 
    same length, and same characters in corresponding positions. 
* Two numbers are strictly equal when they are numerically equal (have the 
    same number value). NaN is not equal to anything, including NaN. 
    Positive and negative zeros are equal to one another. 
* Two Boolean operands are strictly equal if both are true or both are false. 
* Two objects are strictly equal if they refer to the same Object. 

null和undefined類型==(但不是===)

Comparison Operators

+0

反對的任何理由? – rahul 2009-11-13 10:39:21

+0

@adamantium:請編輯。自從我的downvote以來,你增加了很多;)原來你完全錯過了這個問題的目標(避開'undefined'),現在你已經解決了這個問題。 – 2009-11-13 10:58:45

0

如果您不在乎它是否爲空或未定義,或爲假或0,並且只是想查看它是否基本「未設置」,則根本不要使用運算符:

if (yourVar) 
+1

唯一的問題是,如果'yourVar'被設置爲0,或'0',或者一個空字符串,或者其他一些其他東西,那麼它仍然會返回'false'。所以這是一個非常糟糕的方法來檢查它是否一般設置;只適用於你**知道**所有可能的值不是*虛假*。 – 2009-11-13 10:39:53

+0

是的。但是,既然他提到了將null和undefined相提並論,我假設他正在做一些事情,並且不必擔心這些問題。 – 2009-11-13 11:17:09

1

「undefined」不是「null」。比較

  • 勺子是空的(= NULL)
  • 沒有勺子(=未定義)

一些事實,可以幫助您進一步

  • 的typeof undefined是「未定義「
  • typeof null is」object「
  • undefined被認爲與nul相等(==)升,並且反之亦然
  • 沒有其他值等於(==)到空值或未定義
0

if (null == yourvar)if (typeof yourvar != 'undefined') 做的非常不同的事情。一個假設變量存在,另一個。我建議不要混合兩者。知道什麼時候在處理它的價值之前期待變量處理它的存在。

相關問題