处理合并案件switch语句中的重复案例 [英] Dealing with combining cases & duplicate cases in switch statements

查看:373
本文介绍了处理合并案件switch语句中的重复案例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可以将共享分配的cases组合起来,对不共享的分配重复case,还是最好让每个分隔开呢?

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 separated?

以一个简单的示例进行说明.case 0180都包含w = 330,因此它们已经合并;分配给x的值各不相同,因此重复进行x分配.

To illustrate with a simple example.. case 0 and 180 both include w = 330 so they have been combined; the value assigned to x is different for each so they are repeated to do the x assignment.

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

推荐答案

switch语句中每个元素要进行多个操作时,最好不要重复两次相同的case.您可以通过汇总位于同一case下的所有代码片段来轻松实现这一目标.

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.

例如,如果要在case 0上执行A并在case 0case 1上执行B,则应该执行以下操作:

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

这将在case 0上执行操作AB,因为case 0上没有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;
}

上面的代码最终将为变量x分配值1.由于第一个case 1中的break语句,第二个case 1表示将永远无法到达x = 2.

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.

因此,如果您必须在case 0case 1上执行不同的操作,但是它们共享一些操作,则最好将重复某些代码行的情况分开,而不是两次编写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;
}

这篇关于处理合并案件switch语句中的重复案例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆