开发者

How do you remember the order of the expressions in a for loop?

It's a pretty simple question, I always have to go check here and then I hit my head and say it's so obvious. But re开发者_JS百科ally after a week of not using it I usually end up writing

for ($i = 1;  $i++; $i <= 10;) {
    echo $i;
} 

some Mnemonic might help


ICE:

  • Initialisation
  • Check
  • Execute


Think logical! The order is the same as the expressions are evaluated.

for ($i = 0; $i < 10; ++$i) {
    echo $i;
}
// is same as
$i = 0; // 1.
while ($i < 10) { //2.
    echo $i;
    ++$i; // 3.
}


They go in order.

for (expr1; expr2; expr3)

expr1: Evaluated once at the beginning of the loop
expr2: Evaluated at the beginning of each iteration of the loop
expr3: Evaluated at the end of each iteration of the loop

You want to initialize first, check the condition second, and increment (or decrement) your counter last.


     START -> CHECK FOR DANGER -> MOVE AHEAD 

for( $i = 0 ;    $i < 100 ;         $i++    )

Hope it helps :-)
Best of luck!


F irst (initialisation) O Only while (condition) R Rolling on (incrementing or decrementing)


I may be daft but don't you want this structure:

for ( $i = 1;  $i <= 10; $i++ )
{
    echo $i;
} 

I don't know of a Mnemonic to remember this structure I've always just seen it as:

STARTING OFF; DO WHILE THIS; PERFORM AFTER EACH ROTATION

Rather:

DEFINE PRIOR TO EXECUTION; DEFINE EXECUTION LIMITS; DEFINE OPERATION FOR EACH ROTATION


Just remember that the guard is always checked before the increment, so you write it before.

If you don't remember the guard is checked before the increment, you're in bigger trouble, because you don't know what the loop will do :p


SAM

  • Start your engine
  • Are we there yet?
  • Move
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜