Technology/JAVA Script 언어

06. JAVA Script 기본 문법 (6) - 반복문

Ermael Starius 2023. 7. 10. 15:21
//  반복문(for / while / do ~ while)
//
//  => 코드가 진행되는 동안 해당 구간의 내용들을 반복하는 논리구조 문법.
//
//
//  1. 반복문(for / while / do ~ while)
//
//  1-1. for 문
//
//  for(초기값; 조건식; 증감식) {
//    
//  }
//
//  => 인덱스 변수 i 는 0 이다. / i 값이 10 보다 작을때 코드를 반복한다. / 코드를 한번 실행하면 i 를 1 증가시킨다.
//
for(let i=0; i<10; i++) {
    console.log("for 문이 실행중이다 : ", i);
}
//
//
//  1-2. 배열과 for 문
//
const Arr = ["one","two","three","four", "five"];

for(let i=0; i<Arr.length; i++) {
    console.log("인덱스 변수 i 값 : ", i);
    console.log("배열의 요소 : ", Arr[i]);
}
//
//
//  연습문제) 0부터 10까지의 숫자들 중 2의 배수만 console.log() 로 출력 하시오.
//
const Arr_01 = [0,1,2,3,4,5,6,7,8,9,10];

for(let i=0; i<=Arr_01.length; i++) {

    even_num = Arr_01[i] * 2;

    if(even_num <= 10) {
        console.log(even_num);
    }

}
//
for(let i=0; i<=10; i++) {

    if(i>0) {
        if(i % 2 === 0) {

            console.log(i + "는 2의 배수 입니다.");

        }        
    }
}
//
//
//  1-3. for ~ in 문
//
//  => 객체의 속성을 반복하여 출력하는 문법.
//
let person = {
    
    name: "신형만",
    age: "35",
    gender: "male",
}

for(let key in person) {
    console.log(key + ": " + person[key]);
}
//
//
//  2. while 문
//
//  => 조건식이 참일 경우 해당 코드를 반복하는 반복문.
//
//    while(조건식) {
//    
//        메인코드;
//        증가식 or 감소식;
//
//    }
//
let i = 0;

while(i < 10) {

    console.log(i);
    i++;

}

console.log("------------------------------------");
//
//
//  연습문제) while 문을 활용하여 3 < x < 100 인 x 값 중에서 5의 배수만을 출력하시오.
//
//
let x = 3;

while(x < 100) {

    if(x % 5 === 0 && x > 3 && x < 100) {

        console.log("5 의 배수 : ", x);

    }

    x++;

}

console.log("------------------------------------");
//
//
//  3. do ~ while 문
//
//  => 해당 코드를 한번 실행 한 후 조건식이 참일 경우 반복하는 반복문.
//
//    do {
//
//       반복될 코드;
//       증가 or 감소식;
//
//    } while(조건식)
//
//
let index = 0;

do {

    console.log(index);
    index++;

} while(index < 10);

console.log("------------------------------------");
//
//
//  4. break 문
//
//  => 반복문에서 해당 구간까지만 반복하고 반복문을 탈출하는 구문.
//
for(let i=0; i<10; i++) {

    if(i === 5) {
        break;
    }

    console.log(i);

}

console.log("------------------------------------");
//
//
//  5. continue 문
//
//  => 반복문에서 해당 구간만 반복을 생략하는 구문.
//
for(let i=0; i<10; i++) {

    if(i === 5) {
        continue;
    }

    console.log(i);

}

console.log("------------------------------------");