为什么('0'?'a':'b')的行为不同于('0'== true?'a':'b') [英] Why does ('0' ? 'a' : 'b') behave different than ('0' == true ? 'a' : 'b')

查看:137
本文介绍了为什么('0'?'a':'b')的行为不同于('0'== true?'a':'b')的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么以下两个语句的结果不同?

Why is the result of the following two statements different?

('0' ? 'a' : 'b') /* -> 'a' */
('0' == true ? 'a' : 'b') /* -> 'b' */

jsFiddle testcase

编辑:

我应该补充说我怀疑'0'是第一个要转换为要比较的布尔值的语句 - 这应该与'0'== true完全相同
显然这不是真的。

I should add that I suspect the '0' first statement to be cast to boolean to be compared - which should be exactly the same as " '0' == true " Obviously this is not true.

推荐答案

首先,为了完整性:

('0' ? 'a' : 'b') 

'a',因为'0' 非空字符串,总是计算为 true

is 'a', because '0' is a non-empty string, which always evaluates to true:


String :如果参数为空String(其长度为零),则结果为 false ;
否则结果为 true






现在'0'== true

这里将进行两次类型转换。我们可以在规范中遵循这一点,第11.9.3节,抽象等式比较算法

Two type conversions will take place here. We can follow this in the specification, section 11.9.3, The Abstract Equality Comparison Algorithm.

操作数表示为 x y x == y )。

The operands are denoted as x and y (x == y).

在我们的例子中, x 是一个字符串('0')和 y 是一个布尔值( true )。因此执行步骤7:

In our case, x is a string ('0') and y is a Boolean (true). Hence step 7 is executed:


如果Type(y)是布尔值,则返回比较结果x == ToNumber(y)。

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

当布尔值转换为数字时,进行以下转换

When booleans are converted to numbers, the following conversion takes place:


布尔值:结果为 1 ,如果参数是 true 。如果参数为 false ,则结果为 +0

Boolean: The result is 1 if the argument is true. The result is +0 if the argument is false.

现在我们有

'0' == 1

与步骤5中的条件匹配:

which matches the condition in step 5:


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

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

如何将字符串转换为数字更多复杂但当然也可以在规范中找到。

How strings are converted to numbers is more complex but of course can also be found in the specification.

所以最后的比较是

0 == 1

false (步骤1. a.vi。)

which is false (step 1. a. vi.)

这篇关于为什么('0'?'a':'b')的行为不同于('0'== true?'a':'b')的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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