Dealing with combining cases & duplicate cases in switch statements

前端 未结 4 632
猫巷女王i
猫巷女王i 2021-01-15 14:28

Is it okay to combine cases that share assignments and repeat the case for assignments that are not shared, or is it preferred to just keep each se

4条回答
  •  温柔的废话
    2021-01-15 15:00

    When it comes to do more than one operation per element in a switch statement, it's always better to not repeat the same case twice. You can easily achieve this by summing up all the fragments of code that are under the same case.

    For example, if you want to perform operation A on case 0 and operation B on case 0 and case 1 then you should do something like this:

    switch(variable) {
        case 0:
            // operation A;
        case 1:
            // operation B;
            break;
    }
    

    This will execute both operation A and B on case 0, because there's no break on case 0.

    Now let's assume you write something like this:

    switch(variable) {
        case 1:
            x = 1;
            break;
        case 1:
            x = 2;
            break;
    }
    

    The above code will end up assigning the value 1 to the variable x. The second case 1, saying x = 2 will never be reached, because of the break statement in the first case 1.

    So if you have got to perform different operations on case 0 and case 1, but they share some operation, that's better to separate the cases repeating some lines of code instead of writing case 1 twice, because this makes your code easier to read and slightly faster.

    So in your code, the best way to achieve what you want is this one:

    switch(window.orientation) {
        case   0:
            x = '-180px';
            w = 330;
            break;
        case 180:
            x = '-80px';
            w = 330;
            break;
        case -90:
        case  90:
            w = 480;
            x = '0';
            break;
    }
    

提交回复
热议问题