如何减少本例中的代码重复
我需要循环一个数字(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 循环?如果有任何其他建议,将不胜感激。
I need to loop through a number (xx). xx always starts at zero. My problem is that if the moveDirection
variable is +1 then xx increases until it reaches the positive of range
. If moveDirection
is -1, then xx decreases until reaching the negative of range
.
In the code below, I have done this by having an if statement test for moveDirection first, then I have duplicated the for loop, and edited the values for each case. My code happens to be in ActionScript3, but the language does not matter.
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;
}
}
}
Is there a better way of doing this, maybe without duplicating the for loop? If there is any other advice, it would be greatly appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
假设 moveDirection 分别为 1 或 -1(向上或向下)。另外,您必须稍微更改范围才能使 != 正常工作。但是,它确实减少了代码。
This assumes that moveDirection will be either 1 or -1 for going up or down, respectively. Also, you'll have to slightly change your range for the != to work properly. But, it does cut down on code.
从代码的外观来看,循环运行的方向并不重要——如果
hitTestPoint
返回true
,您只是返回true
> 对于范围内的某个值。如果是这样,另一种可能性是这样的:From the looks of the code, it doesn't really matter which direction the loop runs -- you're just returning
true
ifhitTestPoint
returnstrue
for some value in the range. If that's so, another possibility would be something like:另一种可能性:
Another possibility:
这是 Java 中的一个示例(另请参阅 ideone.com):
然后您可以执行以下操作:
如果您想适应非单位步骤,最简单的定义第三个参数如下:
然后你可以这样做:
Here's an example in Java (see also on ideone.com):
Then you can do:
If you want to accommodate non-unit step, it's simplest to define a third parameter as follows:
Then you can do: