代码之家  ›  专栏  ›  技术社区  ›  Adam Harte

如何减少本例中的代码重复

  •  4
  • Adam Harte  · 技术社区  · 14 年前

    我需要循环一个数字(xx)。xx总是从零开始。我的问题是如果 moveDirection range . 如果 移动方向 .

    在下面的代码中,我首先对moveDirection进行if语句测试,然后复制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 回复  |  直到 14 年前
        1
  •  10
  •   fire.eagle    14 年前
    for (xx = 0; xx != range; xx += moveDirection)
    {
        if (hitTestPoint(xx, yy))
        {
            return true;
        }
    }
    

    这假设moveDirection对于向上或向下分别为1或-1。此外,您还必须稍微更改!=正常工作。但是,它确实减少了代码。

        2
  •  1
  •   Jerry Coffin    14 年前

    true 如果 hitTestPoint 退货 范围内的某个值。如果是这样,另一种可能是:

    var start:int = min(0, range);
    var stop:int = max(0, range);
    
    for (xx = start; xx!=stop; xx++)
        if (hitTestPoint(xx,yy)
            return true;
    
        3
  •  1
  •   Mike Dunlavey    14 年前

    另一种可能性:

    int i;
    for (i = abs(range), xx = 0; --i >= 0; xx += moveDirection){
      if (hitTestPoint(xx, yy) return true;
    }
    
        4
  •  0
  •   polygenelubricants    14 年前

    see also on 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