JavaScript相等运算符 [英] Javascript equality operators

查看:63
本文介绍了JavaScript相等运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在David Flanagan的Javascript指南中,有一条语句:

In David Flanagan's Javascript guide, there is a statement:


==运算符从不尝试将其操作数转换为布尔值

the == operator never attempts to convert its operands to boolean

所以在这里我做了一点测试:

So here I did a little test:

var a = false;
var b = ""; // empty string
a == b; //returns true

查看抽象平等比较算法有一个重点:


e。如果Type(x)为布尔值,则如果x和y均为true或均为false,则返回true。否则,返回false。

e. If Type(x) is Boolean, return true if x and y are both true or both false. Otherwise, return false.

如果y是字符串数据类型(不进行转换),则x和y都如何为真?

How can x and y be both true if y is string data type (without conversion)?

推荐答案

内幕发生的事情是


如果 Type(x) Boolean ,则返回比较结果 ToNumber(x) == y

If Type(x) is Boolean, return the result of the comparison ToNumber(x) == y.



Number(false) == ""

其后是


如果 Type(x) Number Type(y) String ,返回比较结果 x == ToNumber(y)

If Type(x) is Number and Type(y) is String, return the result of the comparison x == ToNumber(y).



Number(false) == Number("") -> 0 == 0




如果y,x和y都为真是字符串数据类型(不转换)?

How can x and y be both true if y is string data type (without conversion)?

它们都不都是 true ,但是在强制类型之后它们的值相等。

They are not both true, but after type coercion their values are equal.


==运算符从不尝试将其操作数转换为布尔值

the == operator never attempts to convert its operands to boolean

这是正确的,如果检查比较算法,您会发现类型永远不会隐式转换为 Boolean

And that is correct, if you check the comparison algorithm you will find that types are never implicitly casted to Boolean.

引用:

  • 11.9.3 The Abstract Equality Comparison Algorithm
  • 9.3 ToNumber

这篇关于JavaScript相等运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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