You get a bonus - 1 coin for daily activity. Now you have 1 coin

While, for loops

Lecture




  1. while
  2. Loop do..while
  3. Cycle for

When writing scripts, it often becomes necessary to do the same type of action many times.

For example, remove items from the list one by one. Or just go through all the numbers from 1 to 10 and execute the same code for each one.

For multiple repetitions of a single piece of code - cycles are provided.

while

The while has the form:

while (условие) {
   // код, тело цикла
}
As long as the условие is true, the code from the loop body is executed.

For example, the loop below displays i while i < 3 :

1 var i = 0;
2 while (i < 3) {
3    alert(i);
4    i++;
5 }

Scientifically repeating a loop is called “iteration.” The loop in the example above performs three iterations.

If i++ in the code above, the loop would be executed (in theory) forever. In practice, the browser will display a message about the hung script and the visitor will stop it.

The endless loop can be made simpler:

while ( true ) {
   // ...
}

The condition in brackets is interpreted as a boolean value, therefore instead of while (i!=0) usually write while (i) :

1 var i = 3;
2 while (i) { // при i=0 значение в скобках будет false и цикл остановится
3    alert(i);
4    i--;
5 }

Loop do..while

The condition check can be placed under the loop body using the special syntax do..while :

do {
   // тело цикла
} while (условие);

The cycle described in this way first executes the body and then checks the condition.

For example:

1 var i = 0;
2 do {
3    alert(i);
4    i++;
5 } while (i < 3);

The syntax do..while rarely used because the usual while clearer - it does not have to look for a condition in your eyes and wrestle with why it is checked at the end.

Importance: 3

What is the last value the code will display? Why?

1 var i = 3;
2
3 while (i) {
4    alert(i--);
5 }

Decision

Answer: 1 .

1 var i = 3;
2
3 while (i) {
4    alert(i--);
5 }

Each run of the loop decreases i . The while(i) check will give a “stop” signal when i = 0 .

Accordingly, the steps of the cycle:

1 var i = 3
2 alert(i--); // выведет 3, затем уменьшит i до 2
3
4 alert(i--) // выведет 2, затем уменьшит i до 1
5
6 alert(i--) // выведет 1, затем уменьшит i до 0
7
8 // все, проверка while(i) не даст выполняться циклу дальше

[Open task in new window]

Cycle for

The most commonly used for loop. It looks like this:

for (начало; условие; шаг) {
  // ... тело цикла ...
}

For example, the loop below displays values ​​from 0 to 3 (not including 3 ):

1 var i;
2
3 for (i=0; i<3; i++) {
4    alert(i);
5 }

  • The beginning i=0 is performed when entering the cycle.
  • The condition i<3 checked before each iteration.
  • The i++ step is performed after each iteration, but before checking the condition.

In the loop, you can also define a variable:

for ( var i=0; i<3; i++) {
   ...
}

Any for part may be omitted.

For example, you can remove the начало :

var i = 0;
for (; i<3; i++) ...

You can remove the step:

1 var i = 0;
2 for (; i<3; ) {
3   // цикл превратился в аналог while (i<3)
4 }

And you can generally remove everything by getting an infinite loop:

for (;;) {
   // будет выполняться вечно
}

At the same time the semicolons themselves ; must be present, otherwise there will be a syntax error.

for..in

There is also a special for..in construct for for..in over the properties of an object.

We will meet her later when we talk about objects.

Importance: 4

For each cycle, write down what values ​​it displays. Then compare with the answer.

  1. Prefix option
    var i = 0;
    while (++i < 5) alert(i);
  2. Postfix option
    var i = 0;
    while (i++ < 5) alert(i);
Decision
  1. 1 to 4
    1 var i = 0;
    2 while (++i < 5) alert(i);
    The first value is i=1 , since operation ++i first increase i , and then the comparison and execution of the alert will occur.

    Further 2,3,4.. Values ​​are displayed one after another. For each value, an increase occurs first, and then a comparison, since ++ stands before the variable.

    When i=4 , i will increase to 5 , and then a comparison of while(5 < 5) is wrong. Therefore, the cycle will stop there and the value 5 will not be displayed.

  2. From 1 to 5
    1 var i = 0;
    2 while (i++ < 5) alert(i);
    The first value is i=1 . Let us dwell on it in more detail. The i++ operator increments i , returning the old value, so that in comparison i++ < 5 old i=0 will participate.

    But the subsequent alert call no longer applies to this expression, so it will receive a new i=1 .

    Then 2, 3, 2,3,4.. For each value, a comparison occurs first, and then an increase, and then an alert .

    The end of the cycle: while i=4 a comparison will occur while(4 < 5) is true, then i++ will work, increasing i to 5 , so the value 5 will be displayed. It will be the last.

[Open task in new window]

Importance: 4

For each cycle, write down what values ​​it displays. Then compare with the answer.

  1. Postfix form:
    for ( var i=0; i<5; i++) alert(i);
  2. Prefix form:
    for ( var i=0; i<5; ++i) alert(i);
Decision

Answer: from 0 to 4 in both cases.

1 for ( var i=0; i<5; ++i) alert(i);
2
3 for ( var i=0; i<5; i++) alert(i);

This result is due to the for work algorithm:

  1. Perform assignment i=0
  2. Check i<5
  3. If true, execute the body of the alert(i) loop, then execute i++

The increase in i++ is performed separately from the verification of condition (2), the value of i is not used, therefore there is no difference between i++ and ++i .

[Open task in new window]

Importance: 1

Check out the tutorial / intro / source / loop.html page.

Rewrite the code, replacing the for while with a while , without changing the behavior of the loop.

Decision

tutorial / intro / loop.html.

[Open task in new window]

Importance: 5

Write a loop that prompts the prompt to enter a number greater than 100 . If the visitor entered another number - ask to enter again, and so on.

The cycle should ask the number until either the visitor enters a number greater than 100 , or does not press the Cancel button (ESC).

It is assumed that the visitor enters only numbers.

An example of work.

Decision

Decision:

1 var num;
2
3 do {
4    num = prompt( "Введите число больше 100?" , 0);
5 } while (num <= 100 && num != null );

In action: tutorial / intro / endless_loop.html

The do..while repeats while two checks are true:

  1. Check num <= 100 - that is, the entered number is still less than 100 .
  2. Check num != null - the value null means that the visitor clicked "Cancel", in this case, the cycle must also be stopped.

By the way, comparing num <= 100 when entering null will give true , so the second check is necessary.

created: 2014-10-07
updated: 2024-11-14
335



Rating 9 of 10. count vote: 2
Are you satisfied?:



Comments


To leave a comment
If you have any suggestion, idea, thanks or comment, feel free to write. We really value feedback and are glad to hear your opinion.
To reply

Scripting client side JavaScript, jqvery, BackBone

Terms: Scripting client side JavaScript, jqvery, BackBone