Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
968 views
in Technique[技术] by (71.8m points)

javascript - Is there a more compact way of checking if a number is within a range?

I want to be able to test whether a value is within a number range. This is my current code:

if ((year < 2099) && (year > 1990)){
    return 'good stuff';
}

Is there a simpler way to do this? For example, is there something like this?

if (1990 < year < 2099){
    return 'good stuff';
}
See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

In many languages, the second way will be evaluated from left to right incorrectly with regard to what you want.

In C, for instance, 1990 < year will evaluate to 0 or 1, which then becomes 1 < 2099, which is always true, of course.

Javascript is a quite similar to C: 1990 < year returns true or false, and those boolean expressions seem to numerically compare equal to 0 and 1 respectively.

But in C#, it won't even compile, giving you the error:

error CS0019: Operator '<' cannot be applied to operands of type 'bool' and 'int'

You get a similar error from Ruby, while Haskell tells you that you cannot use < twice in the same infix expression.

Off the top of my head, Python is the only language that I'm sure handles the "between" setup that way:

>>> year = 5
>>> 1990 < year < 2099
False
>>> year = 2000
>>> 1990 < year < 2099
True

The bottom line is that the first way (x < y && y < z) is always your safest bet.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...