前端令人头疼的相等比较(js的==和===)

在JavaScript中有两种相等比较(相等==、全等===)

	1 === 1 //true
	1 === '1' //false
	'1' === 1 //false
	'1' === '1' //true

上面的结果没有疑问,但是如果是相等运算符(== )的话,那么全部都是true,因为==涉及了转换


“The comparison x == y, where x and y are values, produces true or false.”
(翻译:相等运算符用于比较两个值,返回true或false。)

规则如下(英文难看?下面有翻译,规则难懂?我总结了自己的,希望能帮上忙哈):

  • ReturnIfAbrupt(x).
  • ReturnIfAbrupt(y).
  • If Type(x) is the same as Type(y), then
  • Return the result of performing Strict Equality Comparison x === y.
  • If x is null and y is undefined, return true.
  • If x is undefined and y is null, return true.
  • If Type(x) is Number and Type(y) is String, return the result of the comparison x == ToNumber(y).
  • If Type(x) is String and Type(y) is Number, return the result of the comparison ToNumber(x) == y.
  • If Type(x) is Boolean, return the result of the comparison ToNumber(x) == y.
  • If Type(y) is Boolean, return the result of the comparison x == ToNumber(y).
  • If Type(x) is either String, Number, or Symbol and Type(y) is Object, then return the result of the comparison x > * == ToPrimitive(y).
  • If Type(x) is Object and Type(y) is either String, Number, or Symbol, then return the result of the comparison > *ToPrimitive(x) == y.
    *Return false.

翻译:

  • 如果x不是正常值(比如抛出一个错误),中断执行。
  • 如果y不是正常值,中断执行。
  • 如果Type(x)与Type(y)相同,执行严格相等运算x === y。
  • 如果x是null,y是undefined,返回true。
  • 如果x是undefined,y是null,返回true。
  • 如果Type(x)是数值,Type(y)是字符串,返回x == ToNumber(y)的结果。
  • 如果Type(x)是字符串,Type(y)是数值,返回ToNumber(x) == y的结果。
  • 如果Type(x)是布尔值,返回ToNumber(x) == y的结果。
  • 如果Type(y)是布尔值,返回x == ToNumber(y)的结果。
  • 如果Type(x)是字符串或数值或Symbol值,Type(y)是对象,返回x == ToPrimitive(y)的结果。
  • 如果Type(x)是对象,Type(y)是字符串或数值或Symbol值,返回ToPrimitive(x) == y的结果。
  • 返回false。

我的理解

1. 比较的x和有一个不正常,就停止比较:(function(){console.log('我要抛错啦');throw new Error('123')})() == 1
2. x和y同类型就用===比较
3. x和y一个是null一个是undefined,返回true
4. 数字和字符串比较,字符串转换成数字,最终是两个数字的比较,如果转换出来的不是数字,可能是NaN,就false了
5. 如果有一个是布尔值,将布尔值转换成数字再继续比较,可能是true == '3'  到 1 == '3' 到 1 == 3 到 1 === 3 就是false啦
6. x和y一个是字符串、数字或Symbol,另一个是对象,对象先转换原始值,再比较
7. 不满足上面情况就是返回false

关于ToPrimitive

即将操作数转为原始类型的值.他也是规范中的抽象操作,同样可以翻译为等价的js代码,简单来说对于一个对象obj:

toPrimitive(obj)等价于:先计算obj.valueOf(),如果结果为原始值,则返回此结果;否则.计算obj.toString(),如果结果是原始值,则返回此结果;否则,抛出异常

作者:风起云帆
链接:https://www.jianshu.com/p/87a349434678


如果我说得不够清楚,可以看看前辈的。阮一峰 - 读懂 ECMAScript 规格

猜你喜欢

转载自blog.csdn.net/Ton_One/article/details/82823606