First, for completeness:
('0' ? 'a' : 'b')
is 'a'
, because '0'
is a non-empty string, which always evaluates to true
:
String: The result is false if the argument is the empty String (its length is zero);
otherwise the result is true.
Now to '0' == true
.
Two type conversions will take place here. We can follow this in the specification, section 11.9.3, The Abstract Equality Comparison Algorithm.
The operands are denoted as x
and y
(x == y
).
In our case, x
is a string ('0'
) and y
is a Boolean (true
). Hence step 7 is executed:
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:
Boolean: The result is 1 if the argument is true. The result is +0 if the argument is false.
Now we have
'0' == 1
which matches the condition in step 5:
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.
So the final comparison is
0 == 1
which is false
(step 1. a. vi.)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…