有条不紊地改变“for循环”的方向?

时间:2010-11-17 00:57:53

标签: actionscript-3 conditional

是否可以在ActionScript中有条件地更改for循环的方向?

示例:

for(if(condition){var x = 0; x<number; x++}else{var x=number; x>0; x--}){
  //do something
}

3 个答案:

答案 0 :(得分:9)

有趣的要求。保持for的一种方法是:

var start, loop_cond, inc; 
if(condition) 
{ 
    start = 0; 
    inc = 1; 
    loop_cond = function(){return x < number}; 
} 
else 
{ 
    start = number - 1; 
    inc = -1; 
    loop_cond = function(){return x >= 0}; 
} 
for(var x = start; loop_cond(); x += inc) 
{ 
    // do something
}

我们设置起始值,终止条件的函数,以及正或负增量。然后,我们只需调用该函数并使用+=来执行增量或减量。

答案 1 :(得分:6)

ActionScript具有三元运算符,因此您可以执行以下操作:

for (var x = cond ? 0 : number; cond ? x < number : x > 0; cond ? x++ : x--) {
}

但这非常难看。 : - )

你可能还需要/想要在其中加入一些问题。我不确定运算符优先级。

您也可以考虑使用更高阶的功能。想象一下你有:

function forward (count, func) {
    for (var x = 0; x < count; x++) {
        func(x);
    }
}

function backward (count, func) {
    for (var x = count - 1; x >= 0; x--) {
        func(x);
    }
}

然后你可以这样做:

(condition ? forward : backward) (number, function (x) {
     // Your loop code goes here
})

答案 2 :(得分:1)

您可能需要while循环:

var continueLooping, x;

if(condition)
{
  x = 0
  continueLooping = (x < number);
}
else
{
  x = number;
  continueLooping = (x > 0);
}

while (continueLooping)
{
  // do something
  if(condition)
  {
    x++;
    continueLooping = (x < number);
  }
  else
  {
    x--;
    continueLooping = (x > 0);
  }
}

如果你真的想要一个for循环,你应该使用其中两个:

function doSomething()
{
  //doSomething
}

if(condition)
{
  for(var x = 0; x<number; x++)
  {
    doSomething(x);
  }
}
else
{
  for(var x=number; x>0; x--})
  {
    doSomething(x);
  }
}
相关问题