比较运算符==和===在JavaScript中的应用和区别

时间:2017-07-28
==和===在JavaScript有什么区别?相信大家也看过!=和!==比较运算符,本文章向大家介绍js比较运算符双等于==和三等于===的区别以及在什么情况下使用双等于==运算符和三等于===运算符,需要的朋友可以参考一下。

=====类型转换(又称强制),==只需要值相等就会返回true,而===必须值和数据类型都相同才会返回true。

首先,关于Javascript字符串的一些术语等于:Double equals(==)被称为抽象等于比较运算符,而triple equals(===)称为严格等于比较运算符。它们之间的区别可以归纳如下:抽象等于比较运算符(==)只比较值,而不比较数据类型,严格等于比较运算符(===)即比价值也要比较数据类型。请考参考以下示例:

console.log(3 == "3"); // true
console.log(3 === "3"); // false.
console.log(3 == "3"); // true
console.log(3 === "3"); // false.

使用两个相等的符号返回true,因为在进行比较之前将字符串“3”转换为数字3。使用三个等于的迹象表明,这些类型是不同的,并返回false。再看另外几个实例:

console.log(true == '1'); // true
console.log(true === '1'); // false
console.log(true == '1'); // true
console.log(true === '1'); // false

抽象等价比较再次执行类型转换。在这种情况下,布尔值true和字符串'1'都转换为数字1,结果为true。严格相等返回假。

如果你明白你正好在区分==和===的方式。但是,有些情况下,这些操作符的行为是非直观的。我们来看看更多的例子:

console.log(undefined == null); // true
console.log(undefined === null); // false. Undefined and null are distinct types and are not interchangeable.
console.log(undefined == null); // true     
console.log(undefined === null); // false. Undefined and null are distinct types and are not interchangeable.

console.log(true == 'true'); // false. A string will not be converted to a boolean and vice versa.
console.log(true === 'true'); // false
console.log(true == 'true'); // false. A string will not be converted to a boolean and vice versa.
console.log(true === 'true'); // false

下面的例子很有趣,因为它说明字符串文字与字符串对象不同。

console.log("This is a string." == new String("This is a string.")); // true
console.log("This is a string." === new String("This is a string.")); // false
console.log("This is a string." == new String("This is a string.")); // true
console.log("This is a string." === new String("This is a string.")); // false

JavaScript具有严格的和类型转换的等同性比较。为了严格相等,被比较的对象必须具有相同的类型,并且:

  • 当两个字符串具有相同的字符序列,相同的长度和相应位置的相同字符时,它们是严格相等的。
  • 两个数字在数字相等时(数字值相同)严格相等。NaN不等于任何东西,包括NaN。正负零相等。
  • 如果两者都为真或两者均为假,则两个布尔运算符严格相等。
  • 如果两个对象引用相同的对象,则它们是严格相等的。
  • 空和未定义的类型是==(但不是===)。[Ie(Null == Undefined)是真的,但是(Null === Undefined)是false]

实例:

0 == false   // true
0 === false  // false, 因为他们是不同的类型
1 == "1"     // true, automatic type conversion for value only
1 === "1"    // false, because they are of a different type
null == undefined // true
null === undefined // false
'0' == false // true
'0' === false // false