在 JavaScript 中,null
是一个对象。不存在的事物还有另一种价值,undefined
。 DOM 返回null
对于几乎所有无法在文档中找到某些结构的情况,但在 JavaScript 本身中undefined
是使用的值。
其次,不,没有直接的等价物。如果您确实想专门检查null
, do:
if (yourvar === null) // Does not execute if yourvar is `undefined`
如果你想检查一个变量是否存在,只能用try
/catch
, since typeof
将处理未声明的变量和使用以下值声明的变量undefined
作为等价物。
但是,要检查变量是否已声明and is not undefined
:
if (yourvar !== undefined) // Any scope
以前,需要使用typeof
运算符安全地检查未定义,因为可以重新分配undefined
就像一个变量一样。旧的方式看起来像这样:
if (typeof yourvar !== 'undefined') // Any scope
的问题undefined
可重新分配已在 2009 年发布的 ECMAScript 5 中得到修复。您现在可以安全地使用===
and !==
测试undefined
不使用typeof
as undefined
已只读一段时间了。
如果你想知道一个成员是否独立存在但不关心它的值是什么:
if ('membername' in object) // With inheritance
if (object.hasOwnProperty('membername')) // Without inheritance
如果你想知道一个变量是否truthy https://developer.mozilla.org/en-US/docs/Glossary/Truthy:
if (yourvar)
Source http://lists.evolt.org/archive/Week-of-Mon-20050214/099714.html