What Javascript type conversions are happening here?
I found a bug in a script that was written, and I'm having troubles figuring out exactly what is causing the issues. Specifically:
"49px" < 50 === false
There's two different conversions I can think of here:
49 < 50 === true
"49px" < "50" === true
"49" < 50 === true // just for the hell 开发者_如何学Goof it
I fixed it with:
parseInt("49px") < 50 === true
So why does this evaluate to false? What exactly is happening here?
If one operand is a number and another operand is a string, then the string is converted to a number and then the comparison is made.
If the string cannot be converted to a number, it gets converted to NaN
, and the comparison always returns false
.
When javascript is asked to compare a number with something else, it tries to convert that "something else" to a number. In this case, "49px"
evaluates to NaN
so NaN < 50
is false
.
精彩评论