Question

i understand the loops i guess, but im surprised to see in console.log of firebug iterating once more.I expect 10x to iterate(0-9). Why the 10??

$i = 0;

while ($i < 10) {
    console.log($i);//the last time here should be $i=9, not $i=10
    ++$i;
}

// in console log i have(0...10)

while ($i < 10) {
    console.log($i);
    $i++;
}
// in console.log i have doubled 9(0...9,9) Why 9 doubled???

Thanks for you advice

Was it helpful?

Solution

I think what you see is just the result of the last statement, which is $i++ or ++$i. If you directly type this statement in the console, you see a number outputed as well, even if you don't explicitly output it.

For example, if I run the code directly in Firefox's console, I actually see

10
0
1
...
9

The 10 is the result of the last execution of ++$i and the others are the console.log statements, which are only executed after the code terminated (as it seems).

If you use

console.log('Iteration: ' + $i);

then you will see the difference more clearly.


That's also the reason why you see two 9s, since the result of $i++ (where $i = 9) is 9.

OTHER TIPS

I think the "10" and "9" you don't want you're seeing is what is returned in the console.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top