TypeOf未定义,而不是与未定义进行比较

TypeOf undefined instead of comparing against undefined?

本文关键字:未定义 比较 TypeOf      更新时间:2023-09-26

在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是更安全的,因为不是每个变量都属于window范围。

因为typeof操作符不会抛出错误,如果myVar实际上是未定义的

myVar == undefined; // Throws a ReferenceError
typeof myVar == "undefined" //True