4

我需要循环一个数字(xx)。xx 总是从零开始。我的问题是,如果moveDirection变量为 +1,那么 xx 会增加,直到达到 的正数range。如果moveDirection为 -1,则 xx 减小直到达到 的负数range

在下面的代码中,我首先通过 if 语句测试 moveDirection 来做到这一点,然后我复制了 for 循环,并编辑了每种情况的值。我的代码恰好在 ActionScript3 中,但语言无关紧要。

var p:Point;
var xx:int;

if (moveDirection > 0)
{
    for (xx = 0; xx < range; xx++)
    {
        if (hitTestPoint(xx, yy))
        {
            return true;
        }
    }
}
else 
{
    for (xx = 0; xx > range; xx--)
    {
        if (hitTestPoint(xx, yy))
        {
            return true;
        }
    }
}

有没有更好的方法可以做到这一点,也许不需要复制 for 循环?如果有任何其他建议,将不胜感激。

4

4 回答 4

10
for (xx = 0; xx != range; xx += moveDirection)
{
    if (hitTestPoint(xx, yy))
    {
        return true;
    }
}

这假设 moveDirection 将分别为 1 或 -1 表示向上或向下。此外,您必须稍微更改范围才能使 != 正常工作。但是,它确实减少了代码。

于 2010-07-06T22:19:28.790 回答
1

From the looks of the code, it doesn't really matter which direction the loop runs -- you're just returning true if hitTestPoint returns true for some value in the range. If that's so, another possibility would be something like:

var start:int = min(0, range);
var stop:int = max(0, range);

for (xx = start; xx!=stop; xx++)
    if (hitTestPoint(xx,yy)
        return true;
于 2010-07-06T22:31:29.920 回答
1

另一种可能:

int i;
for (i = abs(range), xx = 0; --i >= 0; xx += moveDirection){
  if (hitTestPoint(xx, yy) return true;
}
于 2010-07-07T13:17:10.210 回答
0

这是 Java 中的一个示例(另请参见 ideone.com):

static void go(final int range, final int direction) {
    for (int i = 0; i != direction*range; i += direction) {
        System.out.println(i);
    }       
}

然后你可以这样做:

        go(5, +1); // 0, 1, 2, 3, 4
        go(5, -1); // 0, -1, -2, -3, -4

如果要适应非单元步骤,最简单的方法是定义第三个参数,如下所示:

static void go(final int range, final int step, final int direction) {
    for (int i = 0; i < range; i += step) {
        System.out.println(i * direction);
    }       
}

然后你可以这样做:

        go(10, 3, +1); // 0, 3, 6, 9
        go(10, 3, -1); // 0, -3, -6, -9
于 2010-07-06T22:19:01.900 回答