检查 JavaScript 中是否为 null/未定义
这段代码可以
if (typeof foo != "undefined" && foo !== null) { }
安全地重构为这段代码吗?
if (foo != null) { }
这是完全相同的事情吗? (如果不是,有什么不同?)
Can this code
if (typeof foo != "undefined" && foo !== null) { }
be safely refactored into this code?
if (foo != null) { }
Is it the exact same thing? (And if not, how is it different?)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
并不真地。您将收到
ReferenceError
异常在第二个示例中,如果尚未声明foo
。另一方面,您可以使用 安全地检查未定义的未声明变量
typeof
运算符。Not really. You'll get thrown a
ReferenceError
exception in your second example iffoo
has not been declared.On the other hand, you can safely check for undefined non-declared variables with the
typeof
operator.一个简单的实验将回答这个问题:
上面的例子在许多浏览器中都会产生一个 JavaScript 错误:
“ReferenceError:找不到变量:foo”
。这是因为我们使用了一个先前未在当前作用域中声明为参数或var
的变量。另一方面,
typeof
运算符对尚未定义的变量进行显式调整——它返回'undefined'
,因此:按预期工作。
所以答案是“不”——它们不是同一件事——尽管在某些 javascript 环境中它们的行为方式可能相同,在其他环境中你的第二种形式会当
foo
未定义时产生错误。A simple experiment will answer this question:
the above example yields a javascript error in many browsers:
"ReferenceError: Can't find variable: foo"
. This is because we've used a variable that has not been previously declared as an argument orvar
in current scope.the
typeof
operator, on the other hand, makes an explicit accommodation for variables that haven't been defined -- it returns'undefined'
, so:works as expected.
So the answer is "no" -- they are not the same thing -- though in some javascript environments they may behave the same way, in other environments your second form will produce errors when
foo
is not defined.变量实际上可以保存值
未定义
,如果变量从未被分配过,则该值是默认值。因此,如果您的变量是使用var
声明的或通过赋值给定的值,则foo != null
将起作用,但如果不是,您将得到一个 ReferenceError。因此,这两个片段不等价。如果您可以确定
foo
已声明,那么这比您原来的第二个代码段更安全且更容易理解,假设代码中不存在类似undefined = 42
的内容:Variables can actually hold the value
undefined
, which is the default value if a variable has never been assigned to. Sofoo != null
will work if your variable is declared usingvar
or given a value through assignment, but if it isn't, you will get a ReferenceError. Therefore, the two snippets are not equivalent.If you can be sure that
foo
is declared, this is safe and easier to understand than your original second snippet, assuming that nowhere in the code something likeundefined = 42
exists: