是否可以有條件地更改ActionScript中for循環的方向?有條件地改變「for循環」的方向?
實施例:
for(if(condition){var x = 0; x<number; x++}else{var x=number; x>0; x--}){
//do something
}
是否可以有條件地更改ActionScript中for循環的方向?有條件地改變「for循環」的方向?
實施例:
for(if(condition){var x = 0; x<number; x++}else{var x=number; x>0; x--}){
//do something
}
有趣要求。其中一種方法是:
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
}
我們設置起始值,終止條件的函數,以及正數或負數增量。然後,我們只需調用該函數並使用+=
來做增量或減量。
你可能需要一個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);
}
}
如果你真的想要一個循環,你應該使用它們中的兩種:
function doSomething()
{
//doSomething
}
if(condition)
{
for(var x = 0; x<number; x++)
{
doSomething(x);
}
}
else
{
for(var x=number; x>0; x--})
{
doSomething(x);
}
}
ActionScript中有三元運算符,所以你可以做這樣的事情:
for (var x = cond ? 0 : number; cond ? x < number : x > 0; cond ? x++ : x--) {
}
但這是非常醜陋的。 :-)
您可能還需要/希望將一些parens放在其中。我不確定運營商的優先級。
您可能還會考慮使用更高階的函數。想象一下,你有:
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
})
啊哈,很好地解決 – Josh 2010-11-17 01:11:27