Question is in the title. I've just tried to run next statements in Chrome console and got strange (as for me) result:
true == 'true' // returns false
'true' == true // returns false
Why does it go such way? Why doesn't typecast work there, but in the next statement works?
if ('true') true // returns true
Because they don't represent equally convertible types/values. The conversion used by ==
is much more complex than a simple toBoolean
conversion used by if ('true')
.
So given this code true == 'true'
, it finds this:
"If
Type(x)
isBoolean
, return the result of the comparisonToNumber(x) == y
."
So you see it starts by becoming ToNumber(true) == 'true'
, which is 1 == 'true'
, and then tries again, where it now finds:
If
Type(x)
isNumber
andType(y)
isString
, return the result of the comparisonx == ToNumber(y)
.
So now it's doing 1 == ToNumber('true')
, which is 1 == NaN
, which of course is false
.
The ==
operator uses ECMAScript's abstract equality algorithm which is quite complex. Its exact behavior depends on the types of each argument involved, and each step usually involves another invoking another ECMAScript function.
The if(condition)
statement converts condition
to a boolean using ECMAScript's ToBoolean
which is simple enough to be expressed in a single table. As you can see in the spec, any string is truthy (according to ToBoolean
) if it has a nonzero length.
true = boolean type
'true' = string type
the expression "if ('true')" evaluates the 'true'(string) as true(boolean) on the same way that if('foo') or any other string does.
A non-empty string will return true:
if ('0') true; // true
if ('false') true; // true
if ('anything') true; // true
A null string will return undefined and thus is falsy :
if ('') true; // not true
When comparing types, JavaScript will try to do some magic for you:
if (1 == "1") true; // true
But it fails when converting a string to boolean:
if(true == "true") true; // not true
true is a boolean value 'true' is a string.
you are comparing different data types. look here: http://w3schools.com/js/js_datatypes.asp
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.