简体   繁体   English

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

[英]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) 因此,我有一个函数(我正在使用jQuery ui并在拖动事件上运行此函数,尽管对于这个问题,我认为这并不重要)

Basically I have the following repetitive if else code: 基本上,我有以下重复的if else代码:

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). 我很好奇,如果有在同一行(ISH)写这个,而不是有一个100的方式else if行,如果我希望能够支持100步(共滑块值的部门)。

 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... 这里只显示4个,但想象它还在继续...

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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