简体   繁体   中英

looking for a way to simplify this if/else statement. javascript

So, I have a function (i am workng with jquery ui and running this on drag event, though for this question I don't think that is important)

Basically I have the following repetitive if else code:

And I am curious if there is a way to write this in one line(ish) and not have a 100 else if lines if I want to be able to support 100 steps (divisions of a total slider value).

 var thisPos =  $( ".sliderknob" ).position();

        var x = thisPos.left -  window['sliderhome'].left;

        console.log("(" + x + ")");

        l = Object.keys(obj_frameindex).length;

        framefraction = 290/l;

        if (x>-1 && x<framefraction){
            console.log('frame 1'); 
            frameselector(0); 
            $('#framecounter').html("FRAME " + 1);
        }
        else if (x>framefraction && x<framefraction*2){
            console.log('frame 2'); 
            frameselector(1); 
            $('#framecounter').html("FRAME " + 2);
        }
        else if (x>framefraction*2 && x<framefraction*3){
            console.log('frame 3'); 
            frameselector(2); 
            $('#framecounter').html("FRAME " + 3);
        }
        else if (x>framefraction*3 && x<framefraction*4){
           console.log('frame 4'); 
           frameselector(3); 
           $('#framecounter').html("FRAME " + 4);}    //etc..........

Showing only 4 here, but imagine it goes on...

Any ideas?

Do something like:

if x < 0 { return };
var f = Math.ceil(x / framefraction);
console.log(`frame` + f);
frameselector(f - 1);
$(`#framecounter`).html("FRAME " + f);

One possible approach:

var frameNo = Math.max(0, Math.floor(x / framefraction)) + 1;
console.log('frame ' + frameNo);
frameselector(frameNo - 1);
$('#framecounter').html('FRAME ' + frameNo);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM