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
262 views
in Technique[技术] by (71.8m points)

javascript - Interval comparison doesn't bomb in JS

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 for x<=-1
  • 1 < x < 1 is true for x<=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?

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

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 is 0 < 1 which is true.

  • When -1 < x is true, the second part is 1 < 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 is 0 < -1, which is false.
  • If x = 1, then -1 < 1 is true, so the rest is 1 < -1 which is false.
  • If x = -1, then -2 < -1 is true, so the rest is 1 < -2, which is false.
  • If x = 1, then -2 < 1 is true, so the rest is 1 < -2 which is false.

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

...