--- title: 相等(==) slug: Web/JavaScript/Reference/Operators/Equality tags: - JavaScript - Reference translation_of: Web/JavaScript/Reference/Operators/Equality original_slug: Web/JavaScript/Reference/Operators/相等 ---
{{jsSidebar("Operators")}}

等于运算符(==)检查其两个操作数是否相等,并返回Boolean结果。与严格相等运算符(===)不同,它会尝试强制类型转换并且比较不同类型的操作数。

{{EmbedInteractiveExample("pages/js/expressions-equality.html")}}

语法

x == y

描述

相等运算符(==!=)使用抽象相等比较算法比较两个操作数。可以大致概括如下:

此运算符与严格等于===)运算符之间最显着的区别在于,严格等于运算符不尝试类型转换。相反,严格相等运算符始终将不同类型的操作数视为不同。

例子

没有类型转换的比较

1 == 1;              // true
"hello" == "hello";  // true

与类型转换比较

"1" ==  1;            // true
1 == "1";             // true
0 == false;           // true
0 == null;            // false
0 == undefined;       // false
null == undefined;    // true

const number1 = new Number(3);
const number2 = new Number(3);
number1 == 3;         // true
number1 == number2;   // false

对象比较

const object1 = {"key": "value"}
const object2 = {"key": "value"};

object1 == object2 // false
object2 == object2 // true

比较字符串和String对象

请注意,使用构造的字符串new String()是对象。如果将其中之一与字符串文字进行比较,则该String对象将被转换为字符串文字并对其内容进行比较。但是,如果两个操作数都是String对象,则将它们作为对象进行比较,并且必须引用相同的对象才能进行比较:

const string1 = "hello";
const string2 = String("hello");
const string3 = new String("hello");
const string4 = new String("hello");

console.log(string1 == string2); // true
console.log(string1 == string3); // true
console.log(string2 == string3); // true
console.log(string3 == string4); // false
console.log(string4 == string4); // true

比较日期和字符串

const d = new Date('December 17, 1995 03:24:00');
const s = d.toString(); // for example: "Sun Dec 17 1995 03:24:00 GMT-0800 (Pacific Standard Time)"
console.log(d == s);    //true

技术指标

规范
{{SpecName('ESDraft', '#sec-equality-operators', 'Equality operators')}}

浏览器兼容性

{{Compat("javascript.operators.equality")}}

参见