admin管理员组文章数量:1287505
What I want to do is quite simple in itself, but I'm wondering is there is some really neat and pact way of acplishing the same thing.
I have a float variable, and I want to check if it's value is between 0 and 1. If it's smaller than 0 I want to set it to zero, if it's larger than 1 I want to set it to 1.
Usually I do this:
// var myVar is set before by some calculation
if(myVar > 1){
myVar = 1;
}
if(myVar < 0){
myVar = 0;
}
Does anyone know of a more elegant/pact way of doing this?
What I want to do is quite simple in itself, but I'm wondering is there is some really neat and pact way of acplishing the same thing.
I have a float variable, and I want to check if it's value is between 0 and 1. If it's smaller than 0 I want to set it to zero, if it's larger than 1 I want to set it to 1.
Usually I do this:
// var myVar is set before by some calculation
if(myVar > 1){
myVar = 1;
}
if(myVar < 0){
myVar = 0;
}
Does anyone know of a more elegant/pact way of doing this?
Share Improve this question asked Oct 12, 2012 at 12:59 AsciiomAsciiom 9,9757 gold badges41 silver badges59 bronze badges5 Answers
Reset to default 8One possible solution:
myVar = Math.min(1, Math.max(0, myVar));
Another:
myVar = myVar < 0 ? 0 : myVar > 1 ? 1 : myVar;
Use Math.min and Math.max, and avoid having a condition.
var MAX = 100;
var MIN = 50;
var val = 75;
console.log( Math.max(MIN, Math.min(MAX, val)) );
var val = 49;
console.log( Math.max(MIN, Math.min(MAX, val)) );
var val = 101;
console.log( Math.max(MIN, Math.min(MAX, val)) );
While the Min/Max solution is very succinct, it's far from obvious what is going on.
I would opt for a function that does just what you have:
myVar = constrainToRange(myVar, 0, 1);
function constrainToRange(x, min, max) {
if (x < min) {
x = min;
}
else if( x > max) {
x = max;
}
return x;
}
This is an option which can be expanded very easily to test more than simple min/max:
myVar = parseFloat( (myVar < 0 && '0') || (myVar > 1 && 1) || myVar );
The parseFloat
and returning 0 as a string are important, otherwise it drops through that condition when it should stop there.
Maybe this:
myVal = myVal >= 1 ? 1 : Math.min(Math.abs(myVal), 0)
本文标签:
版权声明:本文标题:javascript - Elegant way of checking if a value is within a range and setting it's value if it falls outside of the rang 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741236312a2363085.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论