一些消息來源表明,有兩種典型的方法來檢查變量是否未定義:爲什麼===代替==未定義
foo === undefined
typeof foo === 'undefined'
但任何人都可以解釋,爲什麼一個使用===
代替==
?
編輯:問題不是關於=== vs ==。這是關於使用正確的運算符'undefined'。 ===和==之間的區別很明顯。但問題是,當檢查值是否未定義時,哪個運算符會更加正確。
一些消息來源表明,有兩種典型的方法來檢查變量是否未定義:爲什麼===代替==未定義
foo === undefined
typeof foo === 'undefined'
但任何人都可以解釋,爲什麼一個使用===
代替==
?
編輯:問題不是關於=== vs ==。這是關於使用正確的運算符'undefined'。 ===和==之間的區別很明顯。但問題是,當檢查值是否未定義時,哪個運算符會更加正確。
當然簡單。你根據它想要的行爲(下面)
null == undefined // true
undefined === null // false
typeof undefined // 'undefined'
typeof null // 'object'
===是一個嚴格的比較。 ===不僅例如比較值,而且數據類型:
"2" == 2 is true
"2" === 2 is false
貌似問題不是==
和===
運營商之間的差異,但大約在什麼情況下應該使用=== 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
===操作測試類型,以及價值。在整個代碼中始終如此使用它有助於防止一些微妙和煩人的錯誤,並且通常是非常好的想法。
"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
雖然比較特殊的未定義的屬性時,可能不是絕對必要的,它肯定不會傷害,而且最好在你的代碼中使用===到處那將是比使用===無處不在除了這個角落的情況。一致性很好。
'==='比較類型*首先*然後值。 '=='比較值和*可能*轉換值,以便類型匹配。 – 2014-11-14 21:43:51
總之:強制 – 2014-11-14 21:44:01
檢查此:http://stackoverflow.com/q/359494/798682 – mattr 2014-11-14 21:44:10