2009-11-13 71 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') 做的非常不同的事情。一个假设变量存在,另一个。我建议不要混合两者。知道什么时候在处理它的价值之前期待变量处理它的存在。

相关问题