检查一个值是否在数字范围内
我想检查一个值是否在可接受的范围内。如果是的话,做某事;否则,其他的东西。
范围为0.001-0.009
。我知道如何使用多个 if
来检查这一点,但我想知道是否有任何方法可以在单个 if
语句中检查它。
I want to check if a value is in an accepted range. If yes, to do something; otherwise, something else.
The range is 0.001-0.009
. I know how to use multiple if
to check this, but I want to know if there is any way to check it in a single if
statement.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(9)
您问的是有关数字比较的问题,因此正则表达式实际上与该问题无关。您也不需要“多个
if
” 语句来执行此操作:您可以自己编写一个“ Between()” 函数:
You're asking a question about numeric comparisons, so regular expressions really have nothing to do with the issue. You don't need "multiple
if
" statements to do it, either:You could write yourself a "between()" function:
这是仅进行一次比较的选项。
Here is an option with only a single comparison.
如果您必须使用正则表达式(实际上,您不应该!),这将起作用:
应该起作用,即
^
之前什么都没有,0.00(注意:
.
字符的反斜杠转义)$
:后跟不为别的If you must use a regexp (and really, you shouldn't!) this will work:
should work, i.e.
^
nothing before,0.00
(nb: backslash escape for the.
character)$
: followed by nothing else如果您已经在使用
lodash
,则可以使用inRange()
函数:https://lodash.com/docs/4.17.15#inRange
If you're already using
lodash
, you could use theinRange()
function:https://lodash.com/docs/4.17.15#inRange
在编写条件之前您必须确定下限和上限
You must want to determine the lower and upper bound before writing the condition
我喜欢 Pointy 的
Between 函数,因此我编写了一个类似的函数,该函数非常适合我的场景。
因此,如果您想查看
x
是否在y
的 ±10 范围内:我用它来检测移动设备上的长按:
I like Pointy's
between
function so I wrote a similar one that worked well for my scenario.so if you wanted to see if
x
was within ±10 ofy
:I'm using it for detecting a long-press on mobile:
如果您希望代码选择特定范围的数字,请务必使用
&&
运算符而不是||
。If you want your code to pick a specific range of digits, be sure to use the
&&
operator instead of the||
.这是一个简短的 ES6 函数:
Here's a short ES6 function:
const inRange = (num, num1, num2) => Math.min(num1, num2) <= num && Math.max(num1, num2) >= num;
如果您想让 inRange 包含在内并且不依赖于范围数字 (num1, num2) 的顺序,则可能是这样。
const inRange = (num, num1, num2) => Math.min(num1, num2) <= num && Math.max(num1, num2) >= num;
Could be like this if you want to make inRange inclusive and not depend on order of range numbers (num1, num2).