2010-11-17 68 views

回答

9

有趣要求。其中一種方法是:

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 
} 

我們設置起始值,終止條件的函數,以及正數或負數增量。然後,我們只需調用該函數並使用+=來做增量或減量。

+0

啊哈,很好地解決 – Josh 2010-11-17 01:11:27

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); 
    } 
} 

如果你真的想要一個循環,你應該使用它們中的兩種:

function doSomething() 
{ 
    //doSomething 
} 

if(condition) 
{ 
    for(var x = 0; x<number; x++) 
    { 
    doSomething(x); 
    } 
} 
else 
{ 
    for(var x=number; x>0; x--}) 
    { 
    doSomething(x); 
    } 
} 
6

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 
}) 
+0

我正要張貼,作爲我對他的第三和最壞的選擇。我打算讓你高興,但僅僅因爲你說它很醜陋':-)'*這不是一個好的解決方案,不要使用它Moshe!* – Josh 2010-11-17 01:14:09

+0

好的。而你的新編輯答案是*光滑*。我同意並希望我現在可以再次upvote :-) – Josh 2010-11-17 01:29:26

+0

謝謝芒! :-) – xscott 2010-11-17 01:30:21