检查JavaScript变量是否为空的最可靠方法是什么?

时间:2009-11-13 10:26:53

标签: javascript

如果我想检查变量是否为空或不存在,最可靠的方法是什么?

有不同的例子:

if (null == yourvar)

if (typeof yourvar != 'undefined')

if (undefined != yourvar)

5 个答案:

答案 0 :(得分:13)

以上都不是。

您不想使用==或其中的各种内容,因为it performs type coercion。如果您确实想检查某些内容是否显式为null,请使用===运算符。

然后,您的问题再次表明您的要求可能缺乏明确性。你具体是指null吗?还是undefined也计算在内? myVar === null肯定会告诉你变量是否为空,这是你问的问题,但这真的是你想要的吗?

请注意this SO question中有更多信息。它不是直接复制,但它涵盖了非常相似的原则。

答案 1 :(得分: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

答案 2 :(得分:1)

“undefined”不是“null”。比较

  • 勺子是空的(= null)
  • 没有勺子(=未定义)

可以帮助您进一步的一些事实

  • typeof undefined是“undefined”
  • typeof null是“object”
  • undefined被认为是等于(==)为null,反之亦然
  • 没有其他值等于(==)为null或undefined

答案 3 :(得分:0)

如果您不关心它是否为null或未定义或为false或0,并且只想查看它是否基本上“未设置”,请不要使用运算符:

if (yourVar)

答案 4 :(得分:0)

if (null == yourvar)if (typeof yourvar != 'undefined') 做很多不同的事情。一个假设变量存在,另一个假设。我建议不要混淆两者。知道何时期望变量在处理其值之前处理它的存在。

相关问题