Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
284 views
in Technique[技术] by (71.8m points)

javascript - Why does ('0' ? 'a' : 'b') behave different than ('0' == true ? 'a' : 'b')


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...