AS3用switch语句替代if和else if语句

4

我正在尝试用 switch 语句替换我的 ifelse if 语句。

Ball 类来自一个外部的 action script 文件,其中有一个变量,我将球的半径传递给它(radius = 30)。

我该如何将 if 和 else if 语句转换为 switch 语句?

代码:

private var ball:Ball;

private var left:Number = 0;
private var right:Number = stage.stageWidth;
private var top:Number = 0;
private var bottom:Number = stage.stageHeight;    

    if(ball.x >= right + ball.radius)
    {
        ball.x = left - ball.radius;
    }

    else if(ball.x <= left - ball.radius)
    {
        ball.x = right + ball.radius;
    }

    if(ball.y >= bottom + ball.radius)
    {
        ball.y = top - ball.radius;
    }

    else if(ball.y <= top - ball.radius)
    {
        ball.y = bottom + ball.radius;
    } 

谢谢您。

我认为在这里你不应该使用“switch”。在你的情况下,“if”语句看起来更好。 - AtomicRobot
好问题。使用switch比大量的“else if”更加简洁美观。它们也更快。 - BadFeelingAboutThis
2个回答

3
这里有一个小技巧 - 在情况(case)而非开关(switch)下进行不等式的评估:
 switch(true) {
     case ball.x >= right + ball.radius:
         ball.x = left - ball.radius;
         break;
     case ball.x <= left - ball.radius:
         ball.x = right + ball.radius;
         break;
 }

switch(true){
     case (ball.y >= bottom + ball.radius):
         ball.y = top - ball.radius;
         break;
     case (ball.y <= top - ball.radius):
         ball.y = bottom + ball.radius;
         break;
} 

1

将switch语句视为IF语句的升级版。
基本上,您正在将switch语句评估为case语句。
Switch语句按自上而下的顺序进行评估,因此一旦找到匹配项,它将在运行该case中的代码后跳出switch。
此外,在您的情况下,您希望保持X和Y分开。

switch(true){
  case (ball.x >= right + ball.radius):
    ball.x = left - ball.radius;
    break;
  case (ball.x <= left - ball.radius):
    ball.x = right + ball.radius;
    break;
  default:
    // no match
}

switch(true){
  case (ball.y >= bottom + ball.radius):
    ball.y = top - ball.radius;
    break;
  case (ball.y <= top - ball.radius):
    ball.y = bottom + ball.radius;
    break;
  default:
    // no match
} 

好��,让我试着理解一下。switch(true)if(ball.x >= right + ball.radius) 是一样的吗?因为所有的 if 语句都是在检查条件是否为真或假,这就是为什么你在 switch(true) 中写入 true 的原因吗? - Scope
一个 switch 语句按顺序遍历每个 case 语句,如果 case 语句与 switch 条件匹配(在这种情况下为 true),则它将执行该 case 中的代码并继续执行下一个 case(除非它到达 break;,然后它将退出 switch),如果它没有到达 break,则会执行 default: 块中的内容。 - BadFeelingAboutThis
所以,switch语句并不是被美化的“if”条件,因为你可以运行多个case语句 - 如果你想退出switch并防止其他语句被评估,你必须手动使用“break”关键字。 - BadFeelingAboutThis
不 - switch(true) 只是让您进入switch语句,它总是发生(true),然后在每个case语句中对位置进行评估。如果您计划扩展比较的数量,则switch很有效。如果您放置switch(false),它也可以工作 - 基本上它需要一个布尔值。 - Gone3d
不,它与说if(ball.x >= right + ball.radius)并不相同——在switch中没有对该语句进行评估。switch(true)表示case条件为真。 switch(false)表示case条件为假。如果条件案例(ball.x >= right + ball.radius)== true —>则执行该代码,否则检查下一个。我的担忧是Scope认为在switch中评估事物时,实际上只是陈述了需要与之进行比较的评估内容。我刚才是不是让它更加混乱了? - Gone3d

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接