开发者

Simpler alternative to double if statement javascript

I'm looking for a simpler way to write this tiny b开发者_开发技巧it of code:

if (a > max)
    a = max;
if (a < min)
    a = min;

What's the easiest way to do this in javascript?


a = (a > max) ? max : a;
a = (a < min) ? min : a;

or even

a = (a < min) ? min : (a > max) ? max : a;


Use Math.max and Math.min:

a = Math.max(min, Math.min(max, a));

If you desire readability then something like this might be better:

function bounded(val, min, max) {
    if (val < min) {
        return min;
    } else if (val > max) {
        return max;
    } else {
        return val;
    }
}

This is very easy to understand and since it's only defined once the verbosity is not a major problem. Use it like this:

a = bounded(a, 0, 10);


a = Math.max(Math.min(a, max), min);

Is this really simpler?


I think the code is a little hard to interpret for a couple of reasons:

  • Single line ifs split on two lines
  • It is trying to limit a value in a range, but does not make it explicit.

Therefore I find the following indentation with a comment better, simpler and more clear:

// Limit a to the [min,max] interval
if (a > max) a = max;
if (a < min) a = min;

Bonus points: it makes it evident that we are assuming min<max.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜