这两种方法真的有区别吗?
有。
myVariable === (undefined || null)
等同于
myVariable === null
这只有在myVariable为null时才为真,而myVariable为undefined时则为假。相反:
myVariable === undefined || myVariable === null
如果myVariable是undefined或null,则返回true。
是的话,我应该使用哪一个?为什么?
可能都不需要使用。如果你想判断一个变量是否存在,你只能测试全局变量,因为它们是全局对象的属性:
var window = this;
if (varname in window) {
}
在函数执行上下文中,您只能通过使用 try..catch 可靠地测试变量:
try {
var blah = foo;
} catch (e) {
// foo is probably not a variable in scope
}
但这几乎肯定不是一个好主意。请参见 JavaScript检查变量是否存在(已定义/已初始化)-哪种方法更好?。
你应该使用以下代码:
if (typeof varname == 'undefined' || varname === null) {
// varname either does't exist or has a value of undefined or null.
}
测试需要按照这个顺序进行,以便如果“varname”未被声明或创建,
typeof测试会在
null测试之前失败,否则会引发错误。
function IsNullOrUndefined (obj) { return obj === null || typeof obj === 'undefined'; }
- ˈvɔləmyVariable === undefined
并不意味着检查 myVariable 是否为未定义。而且,由于(undefined || true)
总是返回 false,他只是在检查myvariable === false
... - ˈvɔlətypeof()
函数就检查类型...千万别这样做...这是不正确的。由于undefined
是 JavaScript 中的一种类型,你需要检查变量的类型而不是其值 -.-# - ˈvɔlə