js ==、!=、===、!== 的注意点

1.  bool 和 数值型 再进行 ==  比较。会先将 bool 转成数值,true 转成 1, false 转成 0。

console.log( false == 0 );    // 输出 true
console.log( false == 1 );    // 输出 false
console.log( false == 2 );    // 输出 false
console.log( false == -1 );   // 输出 false
console.log( true == 0 );     // 输出 false
console.log( true == 1 );     // 输出 true
console.log( true == 2 );     // 输出 false
console.log( true == -1 );    // 输出 false

2.  对象,数组等非简单类型的比较二者的引用是否相等。

var a = new Array(1,2,3);
var b = a;
var c = new Array(3,2,1);
var d = new Array(1,2,3);
console.log( a == b );  // true
console.log( a == c );  // false
console.log( a == d );  // true

3.  null 与 undefined 相等

var a = null;
var b = undefined;
console.log( a == b );           // true
console.log( a == undefined );   // true
console.log( b == null );        // true

4.  当数值、布尔值、字符串与对象类型比较时,先将对象类型转化成简单类型(先进行valueof(),再进行 tostring(), Date类型先进行tostring(),在进行valueof() )。

5.  等同运算(===),如果二个值的类型不同,这它们不等同,null 与 undefined 不等同。 

var a = null;
var b = undefined;
console.log( a === b );           // false
console.log( a === undefined );   // false
console.log( b === null );        // false

6. != 和 == 运算规则相同,结果相反; !== 和 === 运算规则相同,结果相反

原文地址:https://www.cnblogs.com/lkcc/p/7518322.html