开发者

Javascript expression bug (0 <= 14 < 10)?

How can this be true?

0 <= 14 < 10

I need to evaluate that a number is in between 0 and 10.

But this breaks my logic.

Shouldn't that开发者_运维技巧 expression be false?


This expression:

0 <= 14 < 10

is the same as

(0 <= 14) < 10

which is

1 < 10

true.

What you can do instead is:

if (0 <= x && x < 10) { ...

Python is the only programming language I can think of right now where the expression x < y < z does what you expect it to do.


It's not a bug. It's the way the expression is parsed.

It goes left to right:

0 <= 14 < 10
true < 10
1 < 10
true

As you can see, 0 <= 14 is true, so that's what it's replaced with. true is equal to 1 in JavaScript, and most other C-derived languages.


What you should use is:

(0 <= 14) && (14 < 10)


0 <= 14 < 10
(0 <= 14) < 10
true < 10
1 < 10
true


This expression is not evaluating the way you expect it to. It's equivalent to

 ((0 <= 14) < 10)

So the first one evaluates and returns true, so you then have true < 10, and true < 10 evaluates to true in JavaScript


NO. That is true.

0 <= 14 is true (same as int(1)) and 1 < 10 is true

do this instead:

if(variable > 0 && variable < 10) {
   //do something
}


Also check out: https://developer.mozilla.org/en/JavaScript/Reference/Operators/Operator_Precedence

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜