"=="的对象相等性的标准定义是什么? [英] What is the standard definition of object equality for "=="?

查看:78
本文介绍了"=="的对象相等性的标准定义是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

似乎在对==的普遍理解与实际执行之间存在不匹配.为该问题提供一些背景信息:

There seems to be a mismatch between the common understanding of == and what it actually does. To give some background for the issue:

typeof new Number(1); // returns object
typeof new String(1); // returns object
typeof 1;             // returns number

貌似,NumberString都是object类型.毫不奇怪.但是,对于==来说,事情变得有趣了,当不管其类型如何相等时,它应该返回true.

Seemingly, both Number and String are of object type. No surprise there. However things get interesting for == which should return true when operands are equal regardless of their type.

根据一个有点权威性描述:

According to a somewhat authorative description:

操作员试图 将对象转换为原始值,字符串或数字值, 使用对象的valueOf和toString方法.如果这样尝试 转换对象失败,将生成运行时错误.

Operators attempt to convert the object to a primitive value, a String or Number value, using the valueOf and toString methods of the objects. If this attempt to convert the object fails, a runtime error is generated.

简而言之,==应该通过原始值比较对象.令人惊讶的是:

In short, == should compare objects by their primitive value. Surprisingly:

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 (?)

当两个操作数都是对象时出现,==运算符既不使用toString()也不使用valueOf(),而是其他.

It appears when both operands are objects, the == operator uses neither toString() nor valueOf() but something else.

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

What is the standard definition of object equality for ==?

推荐答案

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

In short, when operands are objects then == compares references.

摘自官方规范,第80页:

11.9.3抽象平等比较算法

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

  • If Type(x) is the same as Type(y), then

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

f.如果x和y指向同一对象,则返回true. 否则,返回false.

f. Return true if x and y refer to the same object. Otherwise, return false.

这篇关于"=="的对象相等性的标准定义是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆