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
if
s 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.
精彩评论