问题
Why doesn't interval comparison bomb in JavaScript?
if(-1 < x < 1) {
console.log('x: ', x)
}
Why are we allowed to do this without getting errors?
Also it seems that:
-1 < x < 1
is true forx<=-1
1 < x < 1
is true forx<=1
-1 < x < -1
is always false-2 < x < 2
is always true
In the last 2 cases it seems it is just comparing the 2 ends of the expressions. How are those expressions evalued?
回答1:
Because JavaScript allows implicit type coercion, in this case from boolean to number. The -1 < x
results in a boolean, which is then implicitly coerced to a number (true = 1, false = 0) for the (result) < 1
part. So:
When
-1 < x
is false, the second part is0 < 1
which is true.When
-1 < x
is true, the second part is1 < 1
which is false.
This is covered in the abstract relational comparison algorithm in the spec, and the various operations it links to.
-1 < x < -1 is always false -2 < x < 2 is always true
In the last 2 cases it seems it is just comparing the 2 ends of the expressions. How are those expressions evalued?
Using x = -1
and x = 1
:
- If
x = -1
, then-1 < x
is false, so the rest is0 < -1
, which is false. - If
x = 1
, then-1 < 1
is true, so the rest is1 < -1
which is false. - If
x = -1
, then-2 < -1
is true, so the rest is1 < -2
, which is false. - If
x = 1
, then-2 < 1
is true, so the rest is1 < -2
which is false.
回答2:
I think that this happens because javascript implicitly considers true
to have the value 1
and false
to have the value 0
.
When you do -1 < x < 1
, what you're actually doing is (-1 < x) < 1
, or true < 1
if x = 0
which is false
.
However, if x=-2
, (-1 < x < -1)
will return true
as false < 1
is true
. Hope this helps.
You can read more about this here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comparison_Operators
回答3:
The reason is that JS interprets your expression.
if((-1 < x) < 1) {
console.log('x: ', x)
}
Trying using braces...
来源:https://stackoverflow.com/questions/53320295/interval-comparison-doesnt-bomb-in-js