Ce qui égale l'opérateur (== vs ===) doit être utilisé dans les comparaisons JavaScript

Mots clés : javascriptoperatorsequalityequality-operatoridentity-operatorjavascript

meilleur 3 Réponses Ce qui égale l'opérateur (== vs ===) doit être utilisé dans les comparaisons JavaScript

vote vote

95

'' == '0'           // false 0 == ''             // true 0 == '0'            // true  false == 'false'    // false false == '0'        // true  false == undefined  // false false == null       // false null == undefined   // true  ' \t\r\n ' == 0     // true 
var a = [1,2,3]; var b = [1,2,3];  var c = { x: 1, y: 2 }; var d = { x: 1, y: 2 };  var e = "text"; var f = "te" + "xt";  a == b            // false a === b           // false  c == d            // false c === d           // false  e == f            // true e === f           // true 
"abc" == new String("abc")    // true "abc" === new String("abc")   // false 
vote vote

90

true == 1; //true, because 'true' is converted to 1 and then compared "2" == 2;  //true, because "2" is converted to 2 and then compared 
true === 1; //false "2" === 2;  //false 
vote vote

79

var a = [1,2,3]; var b = [1,2,3]; var c = a;  var ab_eq = (a === b); // false (even though a and b are the same type) var ac_eq = (a === c); // true 
var a = { x: 1, y: 2 }; var b = { x: 1, y: 2 }; var c = a;  var ab_eq = (a === b); // false (even though a and b are the same type) var ac_eq = (a === c); // true 
var a = { }; var b = { }; var c = a;  var ab_eq = (a === b); // false (even though a and b are the same type) var ac_eq = (a === c); // true 
var a = "12" + "3"; var b = "123";  alert(a === b); // returns true, because strings behave like value types 
var a = new String("123"); var b = "123";  alert(a === b); // returns false !! (but they are equal and of the same type) 

Questions similaires