Mos*_*she 2 conditional actionscript-3
是否可以在ActionScript中有条件地更改for循环的方向?
例:
for(if(condition){var x = 0; x<number; x++}else{var x=number; x>0; x--}){
//do something
}
Run Code Online (Sandbox Code Playgroud)
有趣的要求.保持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
}
Run Code Online (Sandbox Code Playgroud)
我们设置起始值,终止条件的函数,以及正或负增量.然后,我们只是调用函数并使用+=
它来做增量或减量.
ActionScript具有三元运算符,因此您可以执行以下操作:
for (var x = cond ? 0 : number; cond ? x < number : x > 0; cond ? x++ : x--) {
}
Run Code Online (Sandbox Code Playgroud)
但这非常难看.:-)
你可能还需要/想要在其中加入一些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);
}
}
Run Code Online (Sandbox Code Playgroud)
然后你可以这样做:
(condition ? forward : backward) (number, function (x) {
// Your loop code goes here
})
Run Code Online (Sandbox Code Playgroud)