这与 SO 上的许多其他问题类似,但与我能找到的不完全相同。
在 Javascript 中检查未定义值的最佳方法是什么,为什么?
第一个例子:
var a;
if (typeof(a) === 'undefined'){...}
第二个例子:
var a;
if (a === undefined){...}
因此,第一个示例是将类型的名称与字符串进行比较,第二个示例是将变量与 undefined object 进行比较,使用相等运算符检查类型和值是否相同。
哪个更好?或者它们彼此一样好?
请注意,我不是在问 undefined 和 null,或 truthy 或 falsey 之间的任何区别,只是这两种方法中哪一个是正确的和/或更好的。
最佳答案
如果一个变量不存在,那么当你尝试使用它时你会得到一个引用错误——即使你将它与 undefined
进行比较。所以总是使用 typeof
。
> foo === undefined
ReferenceError: foo is not defined
at repl:1:2
at REPLServer.eval (repl.js:80:21)
at Interface.<anonymous> (repl.js:182:12)
at Interface.emit (events.js:67:17)
at Interface._onLine (readline.js:162:10)
at Interface._line (readline.js:426:8)
at Interface._ttyWrite (readline.js:603:14)
at ReadStream.<anonymous> (readline.js:82:12)
at ReadStream.emit (events.js:88:20)
at ReadStream._emitKey (tty.js:320:10)
> typeof foo === "undefined"
true
(错误的)代码也可能覆盖 undefined
,这会导致未定义的值不等于 undefined
。
关于javascript - 我应该使用 (typeof(val) === 'undefined' ) 还是 (val === undefined)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10790300/