在 JavaScript 中,为什么人们会写 typeof myVar == "undefined"
而不是 myVar == undefined
?
是否出于兼容性原因?
最佳答案
这是主要原因:
if(a == undefined) console.log('test')
>> ReferenceError: a is not defined
if(typeof a == "undefined") console.log('test')
>> test
但是如果你运行这个比较:
if(window.a == undefined) console.log('test')
>> test
因此,如果您将 a
用作独立变量,则不能。使用 window
是可能的,使用什么方法并不重要,但正如我在评论中所述,使用 typeof
更安全,因为并非每个变量都属于 窗口
范围。
关于javascript - TypeOf undefined 而不是与 undefined 进行比较?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16394564/