목차

Javascript Break and Continue

  • description : Javascript Break and Continue
  • author : 오션
  • email : shlim@repia.com
  • lastupdate : 2021-05-31


the source of this article

Javascript Break and Continue

The For/Of Loop

break 문은 loop에서 빠져나옵니다(jump out).

continue 문은 loop에서 하나의 반복을 “점프”합니다.

The Break Statement

이전 챕터에서 사용된 break 문을 이미 보았습니다. switch() 문에서 “빠져나오는” 데 사용되었습니다.

break 문을 사용하여 loop 밖으로 이동할 수도 있습니다.

Example

<body>
 
  <h2>JavaScript Loops</h2>
 
  <p>A loop with a <b>break</b> statement.</p>
 
  <p id="demo"></p>
 
  <script>
    var text = "";
    var i;
    for (i = 0; i < 10; i++) {
      if (i === 3) { break; }
      text += "The number is " + i + "<br>";
    }
    document.getElementById("demo").innerHTML = text;
    /*
    The number is 0
    The number is 1
    The number is 2
    */
  </script>
 
</body>


상기 예제에서, break 문은 loop 카운터 (i)가 3 일 때, loop를 종료(loop를 “중단”)합니다.

The Continue Statement

continue 문은, 지정된 조건이 발생하면, 루프에서 하나의 반복을 중단하고 루프에서 다음 반복을 계속합니다.

다음 예제는 3의 값을 건너 뜁니다:

Example

<body>
 
  <h2>JavaScript Loops</h2>
 
  <p>A Loop with a <b>continue</b> statement.</p>
 
  <p>A loop which will skip the step where i = 3.</p>
 
  <p id="demo"></p>
 
  <script>
    var text = "";
    var i;
    for (i = 0; i < 10; i++) {
      if (i === 3) { continue; }
      text += "The number is " + i + "<br>";
    }
    document.getElementById("demo").innerHTML = text;
    /*
    The number is 0
    The number is 1
    The number is 2
    The number is 4
    The number is 5
    The number is 6
    The number is 7
    The number is 8
    The number is 9
    */
  </script>
</body>

JavaScript Labels

JavaScript 문에 레이블을 지정하려면 앞에 레이블 이름과 콜론을 추가합니다:

label:
statements


breakcontinue 문은 코드 블록에서 “빠져나올 수 있는” 유일한 JavaScript 문입니다.

Syntax:

break Labelname;
 
continue Labelname;


continue 문 (레이블 참조 포함 또는 제외)은 하나의 Loop 반복을 건너 뛰는 데만 사용할 수 있습니다.

레이블 참조가 없는 break 문은 loop 또는 switch에서 빠져나오는 데만 사용할 수 있습니다.

레이블 참조를 사용하면, break 문을 사용하여 모든 코드 블록에서 빠져나올 수 있습니다:

Example

<body>
 
  <h2>JavaScript break</h2>
 
  <p id="demo"></p>
 
  <script>
    var cars = ["BMW", "Volvo", "Saab", "Ford"];
    var text = "";
 
    list: {
      text += cars[0] + "<br>";
      text += cars[1] + "<br>";
      break list;
      text += cars[2] + "<br>";
      text += cars[3] + "<br>";
    }
 
    document.getElementById("demo").innerHTML = text;
    /*
    BMW
    Volvo
    */
 
  </script>
</body>


코드 블록은 중괄호 { } 사이의 코드 블록입니다.