[DAY - 14] for, select, while, do~while, break, continue

2023. 3. 22. 19:06·🔥 부트캠프-웹 개발 🔥/JavaScript
  • for
  • 이중 for문
  • select
  • while
  • do~while
  • break
  • continue

 

1) for

for 반복문은 초기값, 조건식, 증감식, 실행문으로 이루어져 있다.

 

    for( let 초기값 ; 조건식 ; 증감식 ) {
        실행문
    }

 

초기값 변수는 i, j, k 순서대로 지정을 해야 하고 조건식은 true/false가 결과로 나온다.

 

    <script>
        'use strict';
        for (let i = 0; i < 5; i++) {
            document.write('HELLO :', i ,'<br>');
        }
    </script>

for

 

i가 0부터 시작하여 document를 출력 하고, i++이므로 1이 되어 for문으로 다시 들어간다.

1<5가 true이므로 다시 document를 출력하고 2가 되어 for문으로 또다시 들어간다.

이 작업을 i<5 결과가 false가 될 때까지 반복을 한다.

 

 

        for (let i = 0; i<=30 ; i+=2) {
            if (i % 2 === 0) {
                document.write(i, '<br>');
            }
        }

 

이처럼 if와 %를 사용해 짝수만 출력되게 할 수도 있다.

 

 

    <script>
        'use strict';
        let dan, result;
        dan = Number(prompt('단을 입력 하세요.'));
        for(let i = 1; i<=9; i++) {
            result = i * dan;
            document.write(dan,' X ',i,' = ',result,'<br>');
        }
    </script>

 

2) 이중 for문

 

for문 안에 for문이 들어가야 할때 사용한다.

 

    <script>
        'use strict';
        for(let i = 0; i <= 3; i++) {
            for(let j = 0; j <= 3; j++){
                document.write('i: '+i+' / '+'j: '+j+'<br>');
            }
            document.write('<br>')
        }
    </script>

 

첫번째 for문의 i가 0일 때 두 번째 for문으로 들어가 j가 조건을 만족(j<=3)할 때까지 i는 0인 채로 j값만 바뀌어서 출력된다.

그 후 i는 다시 첫번째 for문으로 올라와 1이 되어 i<=3을 불만족할 때까지 반복한다.

 

 

        'use strict';
        for (let i = 0; i <5; i++) {
            for (let j = 0; j<=i; j++) {
                document.write('☆');
            }
            document.write('<br>');
        }

 

이처럼 첫번째 변수인 i가 두 번째 for문의 조건식 안에 들어갈 수도 있다.

 

 

3) select

mdn select 예시

<select name="pets" id="pet-select">
    <option value="">--Please choose an option--</option>
    <option value="dog">Dog</option>
    <option value="cat">Cat</option>
    <option value="hamster">Hamster</option>
    <option value="parrot">Parrot</option>
    <option value="spider">Spider</option>
    <option value="goldfish">Goldfish</option>
</select>

 

select는 옵션 메뉴를 제공하는 태그이다.

 

    <script>
        'use strict';

        let month, day, year;
        
        year = '<select>';
            year += '<option> ===연=== </option>';
            for( let i = 2023; i>=1900; i--) {
                year += '<option> '+i+'년 </option>';
            }
            year +='</select>';
        document.write(year);

        month = '<select>';
            month = month + '<option> ===월=== </option>';
            for( let i=1; i<=12; i++) {
            month += '<option> '+i+'월 </option>';
        }
            month += '</select>';
        document.write(month);

        day = '<select>';
            day += '<option> ===일=== </option>';
            for( let i=1; i<=31; i++) {
            day += '<option> '+i+'일 </option>';
        }
            day +='</select>';
        document.write(day);
        
    </script>

 

 

select와 for문을 같이 사용하면 위와 같은 예제도 만들 수 있다.

 

4) while

 

주로 무한 반목을 해야할때 사용한다고 배웠다.

 

    <script>
        'use strict';
        let x = 0; //초기값
        while(x<10) { //조건식
            document.write(x, '<br>'); //실행문
            x++; //증감식
        }
    </script>

 

위의 예제에서 조건식을 1 또는 true로 바꿀 경우 무한 반복하게 된다.

 

 

5) do~while

 

조건식의 결과가 false여도 최초 한번은 실행된다.

        let x = -10;
        do{
            document.write(x,'<br>');
            x++;
        } while (x>10)

 

처음 x 값이 -10으로 조건식인 x>10에 불충족하지만 -10이 출력되었다.

 

6) break

    <script>
        'use strict';
        //break 중단 : 보통 무한 반복할 때 사용
        let x = 0;
        while(true) { //무한반복
            if(x>10) {
                break;
            }
            document.write(x, '<br>');
            x++;
        }
    </script>

 

while의 조건식이 true로 무한반복을 해야하지만 if문에서 x>10을 충족하면 break가 실행되어 while문이 종료되고 그다음줄로 넘어가게 된다.

 

7) continue

        for (let i = 0; i<=10; i++) {
            if (i === 5) {
                continue; // i===5가 true이므로 다시 처음 for문으로
            }
            document.write(i,'<br>');
        }

 

i 값이 5가 될 경우 if문의 true 실행문인 continue가 실행되어 document를 거치지 않고 다시 for문으로 올라가 5만 출력이 되지 않는다.

'🔥 부트캠프-웹 개발 🔥/JavaScript' 카테고리의 다른 글
  • [DAY - 16] this, 매개변수, return, 화살표함수, 콜백함수
  • [DAY - 15] 탬플릿리터널, 함수(function), onclick
  • [DAY - 13] switch~case + if, isNaN
  • [DAY - 12] if, 중첩if, switch~case
Yeonhub
Yeonhub
✨ https://github.com/yeonhub 📧 lsy3237@gmail.com
  • Yeonhub
    비 전공자의 Be developer
    Yeonhub
  • 전체
    오늘
    어제
    • 전체보기 (169)
      • 🔍 Tech 🔍 (19)
        • Front-End (11)
        • Back-End (4)
        • AI (1)
        • Server (1)
        • Etc (2)
      • 💡 원티드 프리온보딩 챌린지 💡 (14)
        • PRE-ONBOARDING_AI (11월) (1)
        • PRE-ONBOARDING_FE (2월) (2)
        • PRE-ONBOARDING_FE (1월) (2)
        • PRE-ONBOARDING_FE (12월) (9)
      • 🔥 부트캠프-웹 개발 🔥 (118)
        • HTML5 (7)
        • CSS3 (21)
        • JavaScript (27)
        • JavaScript_advanced (9)
        • React (24)
        • Next (1)
        • MYSql (5)
        • Node (5)
        • 오늘하날(개인프로젝트) (12)
        • 이젠제주투어(팀프로젝트) (7)
      • 💻 CS 💻 (1)
        • 알고리즘 (1)
      • ⚡ 코딩테스트 ⚡ (11)
        • JavaScript (11)
      • 📚 Books 📚 (6)
        • 클린 아키텍처 (2)
        • 인사이드 자바스크립트 (4)
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
  • 링크

    • Github
  • 공지사항

  • 인기 글

  • 태그

    라스콘
    node fcm
    expo admob
    react vite
    react native expo fcm
    프론트엔드 테스트코드
    react native firebase analytics
    python node
    expo deep linking
    컴파운드 컴포넌트 패턴
    node crontab
    Node
    expo map
    react native admob
    expo 지도
    expo 길찾기
    expo node fcm
    node cron
    라스콘4
    rn bottom sheet
    expo google map
    expo fcm
    node.js fcm
    bottom sheet
    rn admob
    php node
    react native analytics
    javascript fcm
    react native bottom sheet
    expo fcm push
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.3
Yeonhub
[DAY - 14] for, select, while, do~while, break, continue
상단으로

티스토리툴바