试一试
console.log(1 == 1);
// Expected output: true
console.log("hello" == "hello");
// Expected output: true
console.log("1" == 1);
// Expected output: true
console.log(0 == false);
// Expected output: true
语法
js
x == y
描述
相等运算符 (== 和 !=) 提供 IsLooselyEqual 语义。这可以大致总结如下:
- 如果操作数具有相同的类型,则按以下方式进行比较:
- 对象:仅当两个操作数引用同一对象时才返回
true。 - 字符串:仅当两个操作数具有相同字符且顺序相同时才返回
true。 - 数字:仅当两个操作数具有相同的值时才返回
true。+0和-0被视为相同的值。如果任一操作数为NaN,则返回false;因此,NaN从不等于NaN。 - 布尔值:仅当两个操作数都为
true或都为false时才返回true。 - BigInt:仅当两个操作数具有相同的值时才返回
true。 - Symbol:仅当两个操作数引用同一 Symbol 时才返回
true。
- 对象:仅当两个操作数引用同一对象时才返回
- 如果其中一个操作数为
null或undefined,则另一个操作数也必须为null或undefined才能返回true。否则返回false。 - 如果其中一个操作数是对象,而另一个是原始值,则将对象转换为原始值。
- 在此步骤中,两个操作数都将转换为原始值(字符串、数字、布尔值、Symbol 和 BigInt 之一)。其余转换逐案进行。
- 如果它们属于同一类型,则使用步骤 1 进行比较。
- 如果其中一个操作数是 Symbol 而另一个不是,则返回
false。 - 如果其中一个操作数是布尔值而另一个不是,则将布尔值转换为数字:
true转换为 1,false转换为 0。然后再次松散地比较这两个操作数。 - 数字转换为字符串:将字符串转换为数字。转换失败将导致
NaN,这将保证相等性为false。 - 数字转换为 BigInt:按其数学值进行比较。如果数字是 ±Infinity 或
NaN,则返回false。 - 字符串转换为 BigInt:使用与
BigInt()构造函数相同的算法将字符串转换为 BigInt。如果转换失败,则返回false。
松散相等是对称的:对于任何 A 和 B 的值(除了应用转换的顺序),A == B 始终具有与 B == A 相同的语义。
此运算符与严格相等 (===) 运算符之间最显著的区别是,严格相等运算符不尝试类型转换。相反,严格相等运算符始终认为不同类型的操作数是不同的。严格相等运算符本质上只执行步骤 1,然后对所有其他情况返回 false。
上述算法有一个“故意违反”的情况:如果其中一个操作数是 document.all,则将其视为 undefined。这意味着 document.all == null 为 true,但 document.all === undefined && document.all === null 为 false。
示例
不带类型转换的比较
js
1 == 1; // true
"hello" == "hello"; // true
带类型转换的比较
js
"1" == 1; // true
1 == "1"; // true
0 == false; // true
0 == null; // false
0 == undefined; // false
0 == !!null; // true, look at Logical NOT operator
0 == !!undefined; // true, look at Logical NOT operator
null == undefined; // true
const number1 = new Number(3);
const number2 = new Number(3);
number1 == 3; // true
number1 == number2; // false
对象的比较
js
const object1 = {
key: "value",
};
const object2 = {
key: "value",
};
console.log(object1 == object2); // false
console.log(object1 == object1); // true
比较字符串和 String 对象
请注意,使用 new String() 构造的字符串是对象。如果将其中一个与字符串字面量进行比较,则 String 对象将转换为字符串字面量,并比较其内容。但是,如果两个操作数都是 String 对象,则它们作为对象进行比较,并且必须引用同一对象才能成功比较。
js
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
比较日期和字符串
js
const d = new Date("1995-12-17T03: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
比较数组和字符串
js
const a = [1, 2, 3];
const b = "1,2,3";
a == b; // true, `a` converts to string
const c = [true, 0.5, "hey"];
const d = c.toString(); // "true,0.5,hey"
c == d; // true
规范
| 规范 |
|---|
| ECMAScript® 2026 语言规范 # sec-equality-operators |
浏览器兼容性
加载中…