我需要循环一个数字 (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 循环?如果还有其他建议,将不胜感激。
最佳答案
for (xx = 0; xx != range; xx += moveDirection)
{
if (hitTestPoint(xx, yy))
{
return true;
}
}
假设 moveDirection 分别为 1 或 -1(向上或向下)。另外,您必须稍微更改范围才能使 != 正常工作。但是,它确实减少了代码。
关于language-agnostic - 如何减少本例中的代码重复,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3190643/