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 badges
Add a ment  | 

5 Answers 5

Reset to default 8

One 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)

本文标签: