+ 2
I need help on the for loop in JavaScript.
please explain how to or the fundamentals of it I am only 11 so words I will be able to understand would be great thanks
2 Respostas
+ 5
(first part, to fit in post size limit)
A loop is a repeated sequence of instruction...
A 'for' loop is one of the way to do, using a counter (best suited for numbered loops).
A 'for' loop in JS is basically written:
for (/* counter initialization */; /* condition */ ; /* counter incrementation */) {
/* code to be repeatitivly executed */
}
+ counter initialization: here you set the JS instruction to set a variable to its start value, done only once at first start of loops
+ condition: an expression to be evaluate as true or false... result says if loop again, before starting executing the sequence in loop
+ counter incrementation: instruction to modify the counter, done at end of each iteration (one execution of sequence in) of loop
So, if you want to count from 5 to 11 by steps of two, you can do:
for (var counter=5; counter<=11; counter = counter + 2) {
/* do the stuff for each value of counter in 5,7,9,11 */
}
/* at end of loop, counter == 13, because when counter == 11, the loop is executed, then counter is incremented again once, the condition is only evaluate to false at this time, the loop is no more executed, and execution restart on first instruction after the loop block sequence ;) */
Loops, among wich 'for' loops, can be endend before 'normal' end, by using 'continue' and/or 'break' keywords in the block sequence of loop:
+ continue: stop the loop block sequence at this point, and jump to end of iteration, increment counter and go testing loop condition to decide if do another iteration or not...
+ break! stop also the loop block sequence at this point, but jump outside of loop (without incrementing and testing steps) to exit completly and end the loop execution...
(example in next post)
+ 6
(second part: example)
for (var c=42; c>10; c = c/2) {
if (Math.round(c)==c) {
alert(c);
continue;
}
alert('round('+c+') == '+Math.round(c));
c=Math.round(c);
}
alert(c);
This execution will be a bit annoying, but output:
> 42, on first iteration... then continue: c is divided by 2, so equals 21 which is greater than 10
> 21, on second iteration... then continue: c == 10.5 which is still greater than 10
> round(10.5) == 11, on third iteration... then c == 5.5 is no more greater than 10, so loop end.
> 5.5 is the outside loop output.
By adding a 'break' statement, you will get:
for (var c=42; c>10; c = c/2) {
if (Math.round(c)==c) {
alert(c);
continue;
}
alert('round('+c+') == '+Math.round(c));
c=Math.round(c);
break;
}
> 42, on first iteration... then continue: c is divided by 2, so equals 21 which is greater than 10
> 21, on second iteration... then continue: c == 10.5 which is still greater than 10
> round(10.5) == 11, on third iteration... then we break, so loop end, without dividing c nor testing condition.
> 11 is now the outside loop output.