在JavaScript中检查null / undefined [英] Checking for null/undefined in JavaScript
本文介绍了在JavaScript中检查null / undefined的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
此代码可以
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?)
推荐答案
不是真的。您将被抛出 ReferenceError
foo 尚未声明,则第二个示例中的> 异常。
Not really. You'll get thrown a ReferenceError
exception in your second example if foo
has not been declared.
另一方面,您可以使用 typeof
运营商。
On the other hand, you can safely check for undefined non-declared variables with the typeof
operator.
这篇关于在JavaScript中检查null / undefined的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文