1

当我到达证明任何术语向量 answer1 不同于任何术语向量 rightAnswer1 的行时,我需要离开函数开关/案例(在条件范围内:“answer1[i1]!= rightAnswer1[i1]”)

switch (currentFrame)
{
    case 1:
        for (var i1:int = 0; i1 < 8; i1++)
        {
            if (answer1[i1] != rightAnswer1[i1])
            {                   
                anyArray[currentFrame - 1] = 2;
                trace("Answer " + i1 + " is wrong!");
                break; // I need to leave the switch/case function here
            }
        }

        trace("Answer is right!");
        anyArray[currentFrame - 1] = 1;

        break;

    case 2:
        for (var i2:int = 0; i2 < 3; i2++)
        {
            if (answer2[i2] != rightAnswer2[i2])
            {                   
                anyArray[currentFrame - 1] = 2;
                break;
            }
        }           
        anyArray[currentFrame - 1] = 1;
        break;

    default:
        trace("ERROR");
    break;
}

if (anyArray[currentFrame - 1] == 1)
    light.play();
else
    error.play();
4

2 回答 2

8

将标签传递给 break 语句,指示要突破的范围:

outside:
switch (currentFrame)
{
    case 1:
        for (var i1:int = 0; i1 < 8; i1++)
        {
            if (answer1[i1] != rightAnswer1[i1])
            {                   
                anyArray[currentFrame - 1] = 2;
                trace("Answer " + i1 + " is wrong!");
                break outside; 
            }
        }

        trace("Answer is right!");
        anyArray[currentFrame - 1] = 1;

        break;
于 2012-08-23T15:09:20.590 回答
2

虽然您可以添加cleong回答的标签,但我建议避开它们,因为它们往往会使代码不必要地复杂化。每次您认为需要添加标签时,可能有一种更清晰、更清晰的方式来处理这种情况。

例如:在这段特定的代码中,您可以编写一个处理验证的函数,从而消除对标签的需求并消除您案例中的所有冗余。

switch (currentFrame)
{
    case 1:
        validateAnswer(answer1, rightAnswer1);
        break;

    case 2:
        validateAnswer(answer2, rightAnswer2);
        break;

    default:
        trace("ERROR");
        break;
}

……剪……

private function validateAnswer(userAnswer:Array, rightAnswer:Array):Boolean
{
    for (var i:int = 0; i < rightAnswer.length; i++)
    {
        if (userAnswer[i] != rightAnswer[i])
        {                   
            anyArray[currentFrame - 1] = 2; //assuming that anyArray and currentFrame are class members
            return false;
        }
    }           
    anyArray[currentFrame - 1] = 1;
    return true;
}

我相信这样你的代码会更具可读性、可扩展性和更不容易出错。

于 2012-08-23T20:31:21.430 回答