简体   繁体   English

在JavaScript中检查null / undefined

[英]Checking for null/undefined in JavaScript

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?) (如果没有,它有什么不同?)

Not really. 并不是的。 You'll get thrown a ReferenceError exception in your second example if foo has not been declared. 如果未声明foo您将在第二个示例中抛出ReferenceError异常。

On the other hand, you can safely check for undefined non-declared variables with the typeof operator. 另一方面,您可以使用typeof运算符安全地检查未定义的非声明变量。

A simple experiment will answer this question: 一个简单的实验将回答这个问题:

if( foo != null ) {
   alert('foo not null');
}

the above example yields a javascript error in many browsers: "ReferenceError: Can't find variable: foo" . 上面的例子在许多浏览器中产生了一个javascript错误: "ReferenceError: Can't find variable: foo" This is because we've used a variable that has not been previously declared as an argument or var in current scope. 这是因为我们使用了之前未声明为参数的变量或当前范围中的var

the typeof operator, on the other hand, makes an explicit accommodation for variables that haven't been defined -- it returns 'undefined' , so: 另一方面, typeof运算符明确适应'undefined'变量 - 它返回'undefined' ,因此:

if( typeof foo != 'undefined') {
    alert('foo is not defined');
}

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. 所以答案是“不” - 它们不是一回事 - 虽然在某些 javascript环境中它们可能表现相同,但在其他环境中,当foo未定义时,第二种形式会产生错误。

Variables can actually hold the value undefined , which is the default value if a variable has never been assigned to. 变量实际上可以保持undefined的值,如果从未赋值变量,则该值是默认值。 So foo != null will work if your variable is declared using var or given a value through assignment, but if it isn't, you will get a ReferenceError. 因此,如果使用var声明变量或通过赋值给定值,则foo != null将起作用,但如果不是,则会得到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 like undefined = 42 exists: 如果你可以确定声明了foo ,那么这比你原来的第二个片段更安全,更容易理解,假设代码中没有像undefined = 42存在:

if(foo !== undefined && foo !== null) { }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM