[9] JavaScript • 조건문 (4)while, do~while

kangsun·2022년 8월 21일

JavaScript

목록 보기
9/9
post-thumbnail

1️⃣ while

형식

  • while (조건 boolean) { 조건에 맞으면 수행 }
  • while (true) {} 무한LOOP
let a=1;
while(a<=3) {
	document.write(a);
    document.write("JAVA");
    a=a+1;
}//while end

document.write(a);

/*
    while(1<=3) {1 jAVA a=1+1}
    while(2<=3) {2 jAVA a=2+1}
    while(3<=3) {3 jAVA a=3+1}
    while(4<=3) {거짓}
*/

// 결과
1JAVA2JAVA3JAVA

document.write(a); //4

👉 for문과 다르게 document.write(a);는 a변수 4로 출력이된다. 최종적으로 살아있는 a=4이기 때문. while(4<=3)
👉 a변수 선언된 위치가 while문 밖에 있기때문이다.


2️⃣ do~while

형식

  • do {
    조건이 true면 수행
    } while (조건 boolean);
[1]

let b=1;
do {
	document.write(b);
    document.write("PYTHON");
    b=b+1;
} while (b<=3);

/*
   do { 1 Python b=1+1 } while(2<=3)
   do { 2 Python b=2+1 } while(3<=3)
   do { 3 Python b=3+1 } while(4<=3) 문장나감
*/

// 결과
1Python2Python3Python
[2]

let c=5;
do {
	document.write("jQuery");
    c=c+1;
} while (c<=3);

/*
    do { jQuery c=5+1 }O while(6<=3)X
*/

// 결과
jQuery

👉 do~while문은 조건이 틀리더라도 무조건 1번 수행된다.
👉 조건(while)이 뒤에 있기 때문.

profile
코딩 공부 💻

0개의 댓글