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

Break and continue directives

Lecture




  1. Exit: break
  2. Next iteration: continue
  3. Tags

For more flexible loop control, use the break and continue directives.

Exit: break

Exit the cycle is possible not only when checking the conditions and, in general, at any time. This feature is provided by the break directive.

For example, the infinite loop in the example will stop execution when i==5 :

01 var i=0;
02
03 while (1) {
04    i++;
05
06    if (i==5) break ;
07
08    alert(i);
09 }
10
11 alert( 'Последняя i = ' + i ); // 5 (*)

The execution will continue from the line (*) following the loop.

Next iteration: continue

The continue directive terminates the current iteration of the loop. For example, the loop below does not display even values:

1 for ( var i = 0; i < 10; i++) {
2   
3    if (i % 2 == 0) continue ;
4
5    alert(i);
6 }

For even i continue triggered, the block is terminated and control is transferred to for .

Style Board

As a rule, continue and use not to process certain values ​​in a loop.

A loop that processes only a fraction of the values ​​might look like this:

01 for ( var i = 0; i < 10; i++) {
02   
03    if ( checkValue(i) ) {
04      // функция checkValue проверяет, подходит ли i
05
06      // ...
07      // ... обработка
08      // ... этого
09      // ... значения
10      // ... цикла
11      // ...
12
13    }
14 }

Everything is good, but we received an additional level of nesting of curly brackets, without which it is possible and necessary to do .

Much better here to use continue :

01 for ( var i = 0; i < 10; i++) {
02   
03    if ( !checkValue(i) ) continue ;
04  
05    // здесь мы точно знаем, что i подходит
06
07    // ...
08    // ... обработка
09    // ... этого
10    // ... значения
11    // ... цикла
12    // ...
13
14 }

It is impossible to use break / continue to the right of the operator '?'

We can usually replace if with a question mark operator '?' .

That is, write:

1 if (условие) {
2    a();
3 } else {
4    b();
5 }
.. Similar records:
условие ? a() : b();

In both cases, depending on the condition, either a() or b() is satisfied.

But the difference is that the question mark operator is '?' used in the second record returns a value.

Syntax constructs that do not return values ​​cannot be used in the '?' Operator . These include most of the constructions and, in particular, break/continue .

Therefore, this code will lead to an error:

(i > 5) ? alert(i) : (i > 5) ? alert(i) : continue ;

Tags

Sometimes you need to exit multiple levels of a cycle at the same time.

Imagine that you need to enter the values ​​of points. Each point has two coordinates (i, j) . The cycle for entering values i,j = 0..2 may look like this:

01 for ( var i = 0; i < 3; i++) {
02
03    for ( var j = 0; j < 3; j++) {
04     
05      var input = prompt( "Значение в координатах " + i + "," + j, "" );
06
07      if (input == null ) break ; // (*)
08
09    }
10 }
11 alert( 'Готово!' );

Here break used to abort the input if the visitor clicked Отмена . But the usual call break in line (*) cannot interrupt two loops at once. How to interrupt the input completely? One of the ways is to put a label .

The label has the form "имя:" , the name must be unique. It is placed before the loop, like this:

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

You can also make it on a separate line. A call to break outer interrupts the loop control with this label, like this:

01 outer:
02 for ( var i = 0; i < 3; i++) {
03
04    for ( var j = 0; j < 3; j++) {
05     
06      var input = prompt( 'Значение в координатах ' +i+ ',' +j, '' );
07
08      if (input == null ) break outer ; // (*)
09
10    }
11 }
12 alert( 'Готово!' );

The continue directive can also be used with a label. The control will jump to the next iteration of the loop with a label.

Labels can be set including on the block, without a loop:

01 my: {
02
03    for (;;) {
04      for (i=0; i<10; i++) {
05        if (i>4) break my;
06      }
07    }
08   
09    some_code; // произвольный участок кода
10
11 }
12 alert( "После my" ); // (*)

In the example above, break jump over some_code , execution will continue immediately after the my block, from the line (*) . The ability to put a label on a block is rarely used. Usually tags are put before a cycle.

Goto?

Some programming languages ​​have a goto that can transfer control to any part of the program.

break/continue statements are more limited. They work only inside loops, and the label should not be anywhere, but higher in the nesting level.

There is no goto in JavaScript.

Importance: 4

A natural number greater than 1 is called simple if it is not divisible by anything except itself and 1 .

In other words, n>1 is simple if, if divided by any number from 2 to n-1 there is a remainder.

Create a code that displays all the primes from 2 to 10 . The result should be: 2,3,5,7 .

PS The code should also be easily modified for any other intervals.

Decision
Solution scheme

1 Для всех i от 1 до 10 {
2   проверить, делится ли число i на какое-либо из чисел до него
3     если делится, то это i не подходит, берем следующее
4     если не делится, то i - простое число
5 }

Decision

Label Solution:

1 nextPrime:
2 for ( var i=2; i<10; i++) {
3
4    for ( var j=2; j<i; j++) {
5      if ( i % j == 0) continue nextPrime;
6    }
7   
8    alert(i); // простое
9 }

Of course, it can be optimized in terms of performance. For example, check all j not from 2 to i , but from 2 to the square root of i . And for very large numbers, there are more efficient specialized algorithms for checking the simplicity of a number, for example, a quadratic sieve and a sieve of a number field.

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



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