如果值在两个数字之间 [英] if value is between two numbers
问题描述
我希望能够测试一个值是否在数字范围内。这是我的jQuery代码......
I want to be able to test whether a value is within a number range. This is my jQuery code...
if ((year < 2099) && (year > 1990)){
return 'good stuff';
}
在jQuery中有更简单的方法吗?例如,有这样的东西......
Is there a simpler way to do this in jQuery? For example, is there something like this...
if (1990 < year < 2099){
return 'good stuff';
}
推荐答案
在许多语言中,第二种对于你想要的东西,将从左到右错误地评估方式。
In many languages, the second way will be evaluated from left to right incorrectly with regard to what you want.
例如,在C中, 1990<年
将评估为0或1,然后变为 1< 2099
,当然总是如此。
In C, for instance, 1990 < year
will evaluate to 0 or 1, which then becomes 1 < 2099
, which is always true, of course.
Javascript非常类似于C: 1990< year
返回 true
或 false
,这些布尔表达式似乎在数字上比较等于0分别为。
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.
但是在C#中,它甚至不会编译,给你错误:
But in C#, it won't even compile, giving you the error:
错误CS0019:运算符'<'不能应用于'bool'和'int'类型的操作数
error CS0019: Operator '<' cannot be applied to operands of type 'bool' and 'int'
你从Ruby得到了类似的错误,而Haskell告诉你,你不能在同一个中缀表达式中使用<
两次。
You get a similar error from Ruby, while Haskell tells you that you cannot use <
twice in the same infix expression.
在我的脑海中,Python是我唯一能够处理之间设置的语言:
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
底线是第一种方式( x< y& y< z)
始终是您最安全的选择。
The bottom line is that the first way (x < y && y < z)
is always your safest bet.
这篇关于如果值在两个数字之间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!