是否有更紧凑的方法来检查数字是否在某个范围内?
我希望能够测试一个值是否在数字范围内。这是我当前的代码:
if ((year < 2099) && (year > 1990)){
return 'good stuff';
}
有更简单的方法吗?例如,有这样的事情吗?
if (1990 < year < 2099){
return 'good stuff';
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
来自此处的类似解决方案: http://indisnip.wordpress.com/2010/08/26/quicktip-check-if-a-number-is- Between-two-numbers/
From a similar solution here: http://indisnip.wordpress.com/2010/08/26/quicktip-check-if-a-number-is-between-two-numbers/
在许多语言中,第二种方式将根据您想要的内容从左到右错误地进行评估。
例如,在 C 语言中,
1990 < year
将计算为 0 或 1,然后变为1 < 2099
,当然,这总是正确的。Javascript 与 C 非常相似:
1990 < year
返回true
或false
,这些布尔表达式在数字上看起来分别等于 0 和 1。但在 C# 中,它甚至无法编译,并给出错误:
您会从 Ruby 中得到类似的错误,而 Haskell 会告诉您不能在同一个中缀表达式中使用
<
两次。在我的脑海中,Python 是唯一一种我确信能够以这种方式处理“之间”设置的语言:
底线是第一种方式
(x 始终是您最安全的选择。
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 becomes1 < 2099
, which is always true, of course.Javascript is a quite similar to C:
1990 < year
returnstrue
orfalse
, 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:
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:
The bottom line is that the first way
(x < y && y < z)
is always your safest bet.您可以制定自己的方法:
希望这会有所帮助。
最大限度
You could make your own method:
hope this helps.
Max
实现此目的的快速而简单的方法是创建一个如下所示的函数:
然后按如下方式使用它:
或者像这样:
The fast and simple way to make this is to create a function like this:
Then use that as follows:
Or like this:
如果您不喜欢布尔运算符,您可以随时使用嵌套的 if 语句:
If you don't like the boolean operator, you could always use nested if statements: