簡體   English   中英

TypeOf未定義而不是與undefined進行比較?

[英]TypeOf undefined instead of comparing against undefined?

在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范圍。

因為如果myVar實際上是未定義的,則typeof運算符不會拋出Error。

myVar == undefined; // Throws a ReferenceError

typeof myVar == "undefined" //True

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM