开发者

What is the best way to check >= and <= in Javascript?

I have a number.

I then have an if statement that I want to go like this:

if (5 <= variable <= 10)

So if the nu开发者_JS百科mber is between 5 and 10, the statement should be true.

What's the best way to go about this?

Thanks.


it is

if (5 <= variable && variable <= 10)


if ((variable >= 5) && (variable <= 10)) works.

If you do this frequently, consider defining a bounds function:

function inBounds(value, min, max){ return ((value >= min) && (value <= max)); }


Actually, if ( 5>= variable >= 10 ) means if(false) if you means variable between 5, 10 it should be 5 <= variable <=10, and in javascript, the best convention is const value at left, which is from c language if (v=1), if (1=v) problem. so the best is:

if (5 <= variable && 10 >= variable) {


It is my understanding that at the first conditional false, it stops the checking and moves to the next statement.

Given that, you should examine the most often false condition and put it first.

if ((variable >= 5) && (variable <= 10))

if it is more likely to be less than 4 or

if ((variable <= 10) && (variable >= 5))

if the failure of 10 or greater is more likely to occur.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜