while문
while문은 조건식을 만족할때까지 코드를 여러회 반복하여 실행할 수 있습니다.
while문
var 변수 = 초깃값; while(조건식){ 실행문; 증감식; }
1부터 100까지 출력
//1부터 100까지 출력
let i = 1;
while(i <= 100){
document.write(i + ". 실행되었습니다.<br>"); //실행문
i++; //증감식
}
5부터 50까지 출력
//5부터 50까지 출력
let i = 5;
while(i <= 50){
document.write(i + ". 실행되었습니다.<br>");
i++;
}
1부터 100까지 출력(짝수만 출력)
//1부터 100까지 출력(짝수만 출력)
let i = 1;
while(i<=100){
if(i % 2==0){
document.write(i + ". 실행되었습니다.<br>");
}
i++;
}
1부터 100까지 출력(4의 배수만 출력)
//1부터 100까지 출력(4의 배수만 출력)
let i = 1;
while(i<=100){
if(i % 4 == 0){
document.write(i + ". 실행되었습니다.<br>");
}
i++;
}
1부터 100까지 출력(4의 배수와 6의 배수 출력)
//1부터 100까지 출력(4의 배수와 6의 배수 출력)
let i = 1;
while(i<=100){
if(i%4==0 || i%6==0){
document.write(i + ". 실행되었습니다.<br>");
}
i++;
}
1부터 100까지 출력(짝수 파란색, 홀수 빨간색)
//1부터 100까지 출력(짝수는 파란색으로, 홀수는 빨간색으로 출력)
let num = 1;
while(num<=100){
if(num % 2 == 0){
//짝수
document.write(num + "<span style='color:blue'>. 실행되었습니다.<br></span>");
} else{
//홀수
document.write(num + "<span style='color:red'>. 실행되었습니다.<br></span>");
}
num++;
}
1부터 20까지 출력
let num1 = 0;
while(num1 < 20){
num1++;
document.write(num1 + ". 실행되었습니다.<br>");
}
Last updated
Was this helpful?