如何减少此示例中的代码重复

Ada*_*rte 4 language-agnostic optimization for-loop code-duplication

我需要遍历一个数字(xx).xx始终从零开始.我的问题是,如果moveDirection变量是+1,则xx会增加,直到达到正值range.如果moveDirection为-1,则xx减小直到达到负数range.

在下面的代码中,我首先对moveDirection进行了if语句测试,然后我复制了for循环,并编辑了每个case的值.我的代码恰好在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;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

有没有更好的方法来做到这一点,也许没有重复for循环?如果有任何其他建议,将不胜感激.

fir*_*gle 10

for (xx = 0; xx != range; xx += moveDirection)
{
    if (hitTestPoint(xx, yy))
    {
        return true;
    }
}
Run Code Online (Sandbox Code Playgroud)

这假设moveDirection分别为1或-1,分别为up或down.此外,您必须稍微改变您的范围才能使!=正常工作.但是,它确实减少了代码.