我刚刚读了这个优秀的question和顶部 answer关于“== 与 ===”。
var x = undefined;
当检查 x
是否真正等于 undefined
时,以下两种方法都有效。
if(typeof x == "undefined") {
console.log("typeof x == \"undefined\"");
}
if(x === undefined) {
console.log("x === undefined");
}
输出:
typeof x == "undefined"
x === undefined
一种方式是否比另一种方式更惯用?如果是,为什么?
最佳答案
我会说,如果您可以控制 x
的可能值范围,那么检查 x === undefined
是最惯用的方法。例如,如果您有一个返回结果的函数,或者 undefined
如果它遇到错误。
否则,您应该使用 typeof x == 'undefined'
。
需要注意的是,某些表达式和变量可以未定义
,因为它们根本没有定义,而其他表达式和变量则明确定义为未定义
。
如果您尝试这样做:
var x = undefined;
if(typeof x == "undefined") // This works
if(x === undefined) // This works
if(typeof y == "undefined") // This works
if(y === undefined) // This does not work and throws a ReferenceError
所以基本上,如果您无法控制 variable's range,使用 typeof
会更安全、更容易。因为您不必实现异常处理。
关于javascript - 使用 `typeof ==` 和 `===` 检查未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20791383/