在js中,'==' 和 '==='運算符用來比較兩個值是否相等,可是他們對於相等的定義是不一樣的。兩個運算符均可以用來比較任意類型的操做數,若是兩個操做數相等,返回true,不然,返回false。'===' 嚴格相等運算符,用來比較兩個操做數是否嚴格相等。'==' 相等運算符,用來比較兩個操做數是否相等。
詳細信息可參照ECMA標準(戳這裏)。翻譯
== 相等操做符,在比較前會把比較的兩個數轉換成相同的數據類型以後,而後對兩個數進行比較。轉換後,比較方式與 === 相同。code
ECMA中比較規則以下:orm
The comparison x == y, where x and y are values, produces true or false. 1. ReturnIfAbrupt(x). 2. ReturnIfAbrupt(y). 3. If Type(x) is the same as Type(y), then Return the result of performing Strict Equality Comparison x === y. 4. If x is null and y is undefined, return true. 5. If x is undefined and y is null, return true. 6. If Type(x) is Number and Type(y) is String, return the result of the comparison x == ToNumber(y). 7. If Type(x) is String and Type(y) is Number, return the result of the comparison ToNumber(x) == y. 8. If Type(x) is Boolean, return the result of the comparison ToNumber(x) == y. 9. If Type(y) is Boolean, return the result of the comparison x == ToNumber(y). 10. If Type(x) is either String, Number, or Symbol and Type(y) is Object, then return the result of the comparison x == ToPrimitive(y). 11. If Type(x) is Object and Type(y) is either String, Number, or Symbol, then return the result of the comparison ToPrimitive(x) == y. 12. Return false.
翻譯以下:對象
比較 x == y,當x 和 y是正常值時,返回 true 或者 false。索引
簡化一下 ,能夠理解爲:it
'===' 嚴格相等操做符,用來比較兩個操做數是否嚴格相等。form
ECMA中比較規則以下:數據類型
1. If Type(x) is different from Type(y), return false. 2. If Type(x) is Undefined, return true. 3. If Type(x) is Null, return true. 4. If Type(x) is Number, then a. If x is NaN, return false. b. If y is NaN, return false. c. If x is the same Number value as y, return true. d. If x is +0 and y is −0, return true. e. If x is −0 and y is +0, return true. f. Return false. 5. If Type(x) is String, then a. If x and y are exactly the same sequence of code units (same length and same code units at corresponding indices), return true. b. Else, return false. 6. If Type(x) is Boolean, then a. If x and y are both true or both false, return true. b. Else, return false. 7. If x and y are the same Symbol value, return true. 8. If x and y are the same Object value, return true. 9. Return false.
翻譯:方法
若是Type(x)是Number,那麼im
若是Type(x)是String,那麼
簡化一下,能夠理解爲:
若是操做數的數據類型都爲Number,當兩個數的值相同時,返回true, 不然返回 false。
注: -0 === +0 => true +0 === -0 => true NaN 與任何值都不相等,包括他本身。 因此要判斷一個數值是否爲NaN, 可採用 x !== x ,只有NaN 返回true