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

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

问题描述

我们经常在 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
}

不幸的是,当 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 cases:

  1. 变量可以是undefinedundeclared.如果您在 typeof 以外的任何上下文中访问未声明的变量,则会出现错误.
  1. Variables can be undefined or undeclared. You'll get an error if you access an undeclared variable in any context other than typeof.

if(typeof someUndeclaredVar == whatever) // works
if(someUndeclaredVar) // throws error

已声明但未初始化的变量是undefined.

A variable that has been declared but not initialized is undefined.

let foo;
if (foo) //evaluates to false because foo === undefined

  1. 未定义的 properties ,例如 someExistingObj.someUndefProperty.未定义的属性不会产生错误,只会返回 undefined,当转换为布尔值时,其计算结果为 false.所以,如果你不在乎0false,使用 if(obj.undefProp) 就可以了.有一个基于这个事实的常见习语:

  1. 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有属性prop,则赋值给value,否则赋值为默认值defautValue".

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

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

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 中检查未定义或空变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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