寻找一种简化if/else语句的方法.javascript

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

本文关键字:else 语句 javascript 方法 if 一种 寻找      更新时间:2023-09-26

所以,我有一个函数(我正在使用jquery ui并运行这个拖拽事件,尽管对于这个问题,我认为这并不重要)

基本上我有以下重复的if else代码:

我很好奇,如果我想支持100步(总滑块值的除法),是否有一种方法可以在一行(ish)中写入,而不需要100行else if

 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..........

这里只显示4个,但想象一下…

有什么想法吗?

一种可能的方法:

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

执行以下操作:

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