我们经常在JavaScript代码中使用以下代码模式
if (typeof(some_variable) != 'undefined' && some_variable != null)
{
// Do something with some_variable
}
是否有一种不那么冗长的检查方法具有相同的效果?
根据一些论坛和文献,简单地说下面应该有同样的效果。
if (some_variable)
{
// Do something with some_variable
}
不幸的是,当some_variable未定义时,Firebug在运行时将这样的语句计算为错误,而第一个语句对它来说很好。这仅仅是Firebug的一种(不必要的)行为,还是这两种方式之间真的有一些区别?
为了理解,让我们分析一下Javascript引擎在转换undefined、null和”(也是一个空字符串)时返回的值是什么。您可以直接在开发人员控制台检查相同的内容。
你可以看到所有都被转换为false,这意味着所有这三个都是通过javascript假设“缺乏存在”。因此,您不需要像下面这样显式地检查代码中的所有三个。
if (a === undefined || a === null || a==='') {
console.log("Nothing");
} else {
console.log("Something");
}
我还想指出一件事。
布尔(0)的结果是什么?
当然是假的。当0是预期结果中的有效值时,这将在代码中创建一个错误。所以在写代码的时候一定要检查这个。
如果您试图引用一个未声明的变量,那么在所有JavaScript实现中都会抛出一个错误。
对象的属性不受相同条件的约束。如果未定义对象属性,则在尝试访问它时不会抛出错误。在这种情况下,你可以缩短:
if (typeof(myObj.some_property) != "undefined" && myObj.some_property != null)
to
if (myObj.some_property != null)
考虑到这一点,以及全局变量可以作为全局对象(浏览器中的窗口)的属性访问的事实,你可以对全局变量使用以下方法:
if (window.some_variable != null) {
// Do something with some_variable
}
在局部作用域中,确保变量在代码块的顶部声明总是有用的,这将节省重复使用typeof。
你必须区分不同的情况:
变量可以是未定义的或未声明的。如果在typeof以外的任何上下文中访问未声明的变量,将会得到一个错误。
if(typeof someUndeclaredVar == whatever) // works
if(someUndeclaredVar) // throws error
已声明但未初始化的变量是未定义的。
let foo;
if (foo) //evaluates to false because foo === undefined
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
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