2014-11-14 92 views
1

一些消息來源表明,有兩種典型的方法來檢查變量是否未定義:爲什麼===代替==未定義

foo === undefined 
typeof foo === 'undefined' 

但任何人都可以解釋,爲什麼一個使用===代替==

編輯:問題不是關於=== vs ==。這是關於使用正確的運算符'undefined'。 ===和==之間的區別很明顯。但問題是,當檢查值是否未定義時,哪個運算符會更加正確。

+2

'==='比較類型*首先*然後值。 '=='比較值和*可能*轉換值,以便類型匹配。 – 2014-11-14 21:43:51

+0

總之:強制 – 2014-11-14 21:44:01

+4

檢查此:http://stackoverflow.com/q/359494/798682 – mattr 2014-11-14 21:44:10

回答

8

當然簡單。你根據它想要的行爲(下面)

null == undefined // true 
undefined === null // false 
typeof undefined // 'undefined' 
typeof null // 'object' 
+4

'undefined == null // true'對不對? – elclanrs 2014-11-14 21:47:26

+0

是的,在JS中的所有平等運算符都是聯合@elclanrs(注意'b> = a'並不意味着'a <= b':P – megawac 2014-11-14 21:49:05

+0

@elclanrs啊,我明白你在說什麼。megawac,有一個typeo第二行 – 2014-11-14 21:50:46

4

===是一個嚴格的比較。 ===不僅例如比較值,而且數據類型:

"2" == 2 is true 
"2" === 2 is false 
2

貌似問題不是=====運營商之間的差異,但大約在什麼情況下應該使用=== undefined比較時typeof == 'unefined'。那麼..

有兩種方法來檢查未定義的值。

第一種方式是使用嚴格的比較操作===undefined原始的比較:

var a; 
a === undefined; // true 

上面的對比會達到預期效果,只有當變量聲明但未定義的值。 請注意,如果變量從來沒有被宣佈不能使用a === undefined比較,因爲它會拋出引用錯誤:

a === undefined // ReferenceError: a is not defined 

這就是爲什麼在這種情況下typeof比較防彈:

typeof a == 'undefined' // true 

這在兩種情況下都能正常工作:如果變量從未被賦值,並且其值實際上是undefined

再舉一個例子。如果我們要檢查一個prop屬性,它是/可能是丟失:

someObj.prop === undefined // ReferenceError: a is not defined 

typeof someObj.prop == 'undefined' // true 
+0

只要'someObj'已被定義,然後嘗試檢查'someObj.prop === undefined'是否不會引發引用錯誤,它只會返回'true'或'false' – Adam 2014-11-14 22:58:53

+0

你是絕對正確的,問題不在於=== vs ==,而是關於在'undefined'中使用正確的操作符,可惜它有很多缺點,因爲人們急於回答而不考慮問題。 – Oleg 2014-11-15 18:53:08

0

===操作測試類型,以及價值。在整個代碼中始終如此使用它有助於防止一些微妙和煩人的錯誤,並且通常是非常好的想法。

"5" == 5 // True, even though one is a string and the other a number 
"5" === 5 // False because the two variables are of different type 

雖然比較特殊的未定義的屬性時,可能不是絕對必要的,它肯定不會傷害,而且最好在你的代碼中使用===到處那將是比使用===無處不在除了這個角落的情況。一致性很好。