如何在JavaScript中检查未定义或null变量? [英] How to check for an undefined or null variable in JavaScript?

查看:329
本文介绍了如何在JavaScript中检查未定义或null变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们经常在JavaScript代码中使用以下代码模式

We are frequently using the following code pattern in our JavaScript code

if (typeof(some_variable) != 'undefined' && some_variable != null)
{
    // Do something with some_variable
}

是否有一种不那么冗长的检查方式具有相同的效果?

Is there a less verbose way of checking that has the same effect?

根据一些论坛和文献说,只需以下内容应该具有同样的效果。

According to some forums and literature saying simply the following should have the same effect.

if (some_variable)
{
    // Do something with some_variable
}

不幸的是, Firebug some_variable 未定义的情况下评估这样的语句为运行时错误,而第一个就好了它。这只是Firebug的一个(不需要的)行为,还是这两种方式之间确实存在一些差异?

Unfortunately, Firebug evaluates such a statement as error on runtime when some_variable is undefined, whereas the first one is just fine for it. Is this only an (unwanted) behavior of Firebug or is there really some difference between those two ways?

推荐答案

你必须区别对待两种情况之间:

You have to differentiate between two cases:


  1. 未定义的变量,如 foo 。如果在 typeof 以外的任何上下文中访问未定义的变量,则会出现错误。

  1. Undefined variables , like foo. You'll get an error if you access an undefined variable in any context other than typeof.

if(typeof someUndefVar == whatever) // works

if(someUndefVar) // throws error  

因此,对于变量, typeof 检查是必须的。另一方面,它很少需要 - 如果你的变量被定义,你通常知道

So, for variables, the typeof check is a must. On the other side, it's only rarely needed - you usually know if your variables are defined or not.

未定义的属性,如 someExistingObj.someUndefProperty 。未定义的属性不会产生错误,只返回 undefined ,当转换为布尔值时,计算结果为 false 。所以,如果你不关心
0 false ,使用 if(obj.undefProp)没问题。基于这个事实有一个常见的习语:

Undefined properties , like someExistingObj.someUndefProperty. An undefined property doesn't yield an error and simply returns undefined, which, when converted to a boolean, evaluates to false. So, if you don't care about 0 and false, using if(obj.undefProp) is ok. There's a common idiom based on this fact:

value = obj.prop || defaultValue

这意味着如果 obj 具有property prop ,将其分配给 value ,否则分配默认值 defautValue

which means "if obj has the property prop, assign it to value, otherwise assign the default value defautValue".

有些人认为这种行为令人困惑,认为这会导致难以发现的错误并建议使用 运算符中

Some people consider this behavior confusing, arguing that it leads to hard-to-find errors and recommend using the in operator instead

value = ('prop' in obj) ? obj.prop : defaultValue


这篇关于如何在JavaScript中检查未定义或null变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆