问题
I ran across an interesting bug the other day. I was testing an array to see if it evaluated to Boolean false, however just directly evaluating it always returned true:
> !![]
true
Okay, so basically any array I put in there will be true
regardless, right? I run this in the JavaScript console just for fun:
> [] == true
false
What is going on here?
回答1:
It has to do with the The Abstract Equality Comparison Algorithm versus the algorithm used to tranform a value to a boolean.
By looking at the spec, we can see that the point number 9. is the only one that defines what should be happening when Type(left side value) is Object. However it's specifying that the right side value has to be either String or Number.
9 . If Type(x) is Object and Type(y) is either String or Number, return the result of the comparison ToPrimitive(x) == y.
Looking at [] == true
:
typeof []
is 'object'
so we are fine, but typeof true
is not 'string'
or 'number'
, it is 'boolean'
, so it fallback to the last statement, point number 10.
10 . Return false.
However !![]
translates into !!Boolean([])
, and since []
is a thruty value (objects are), it's the same as writing !!true
, which returns true
.
来源:https://stackoverflow.com/questions/19034155/boolean-evaluation-of-javascript-arrays