본문 바로가기

cording/생활코딩

[Java Script] 반복문

반복되게 결과를 도출해낼때 사용한다.

<!DOCTYPE html>
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title></title>
  </head>
  <body>
    <h1>Loop</h1>
    <ul>
      <script>
        document.write('<li>1</li>');
        var i = 0;
        while (i < 3) {
          document.write('<li>2</li>');
          document.write('<li>3</li>');
          i = i + 1;
        }
        document.write('<li>4</li>');
      </script>
    </ul>
  </body>
</html>

<!DOCTYPE html>
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title></title>
  </head>
  <body>
    <h1>Loop</h1>
    <ul>
      <script>
        document.write('<li>1</li>');
        var i = 0;  : 변수 i = 0 일때
        while (i < 3) { : i가 3보다 작으면 (참 Ture) 반복 출력, False 면 반복실행중단
          document.write('<li>2</li>');
          document.write('<li>3</li>');
          i = i + 1; : 이때 i = i + 1;
        }
        document.write('<li>4</li>');
      </script>
    </ul>
  </body>
</html>

 * while (i < 3) :  while () 괄호안에는 Boolean 값 (ture or false) 을 넣어준다. 그리고 {} 안에는 반복할 코드를 넣어주고 반복문이 언제 종료할지 조건을 넣어준다.

이때 while 은 if 처럼 실행 순서를 제어하는 제어문이다. 

** whil(i<3)은 실행이 되지만, while(i&lt3)은 실행이 안된다. &lt 은 html의 문법에서 쓰는 것이기 때문에 js 에서는 <> 로 처리가 가능하다.

 

결과값

 

'cording > 생활코딩' 카테고리의 다른 글

[Java Script] 배열과 반복문의 활용  (0) 2022.03.09
[Java Script] 배열과 반복문  (0) 2022.03.09
[Java Script] 배열  (0) 2022.03.07
[Java Script] 리팩토링 중복의 제거  (0) 2022.03.06
[Java Script] 조건문의 활용  (0) 2022.03.05