"=="的对象相等的标准定义是什么?

Sau*_*aul 9 javascript types operators type-conversion

这里似乎是共同的认识之间的不匹配==,它实际上做什么.为此问题提供一些背景知识:

typeof new Number(1); // returns object
typeof new String(1); // returns object
typeof 1;             // returns number
Run Code Online (Sandbox Code Playgroud)

看似,这两个NumberString是的object类型.这并不奇怪.然而==,true当操作数相等而不管它们的类型时,事情会变得有趣.

根据一个有点权威的说明:

运算符尝试使用对象的valueOf和toString方法将对象转换为原始值,String或Number值.如果此转换对象的尝试失败,则会生成运行时错误.

简而言之,==应该按原始值比较对象.出奇:

var numa = new Number(1);
var numb = new Number(1);
var stri = new String(1);

numa.toString() == stri.toString(); // returns true, as expected
numa.valueOf() == stri.valueOf();   // returns true, as expected

numa == stri; // returns false (?!)
numa == numb; // returns false (?!!!)

numa == numa; // returns true, as expected

var numx = 1;

numa == numx; // returns true (?)
numb == numx; // returns true (?)
stri == numx; // returns true (?)
Run Code Online (Sandbox Code Playgroud)

当两个操作数都是对象时,==操作员既不使用toString()也不使用valueOf()其他操作.

对象相等的标准定义是==什么?

cha*_*aos 5

我相信你在那里看到的,以及"有些权威性的描述"中遗漏的是,==试图将对象转换为原语,当且仅当它的比较是原始的时候.如果两个操作数都是对象,则将它们作为对象进行比较,并且只有当它们是同一个对象时,相等性测试才为真(即相同的实例 - 具有相同属性的不同对象不同,如您所见numa == numb).


Yos*_*shi 3

简而言之,当操作数是对象时,然后==比较引用。

来自官方规范,第 80 页:

11.9.3 抽象相等比较算法

  • 如果 Type(x) 与 Type(y) 相同,则

    a - e 省略,因为不适用于对象

    F。如果 x 和 y 引用同一个对象,则返回 true。否则,返回 false。