🐶 etc/2022기록

[20230627]반복문,for,while,do while,forEach,for in,for of

서카츄 2023. 6. 27. 11:21
    let i = 0;
            document.write(i+'<br>');
            i += 2;
            document.write(i+'<br>');
            i += 2;
            document.write(i+'<br>');
            i += 2;

2/4/6

 

 

 

 

            let i = 0;
            document.write(i+'<br>');
            i += 2;
            document.write(i+'<br>');
            i += 2;
            document.write(i+'<br>');
            i += 2;

            for(초기문; 조건문; 증감문){
                //반복할 구문
            }

초기문 : 초기값을 설정한다

조건문 : 언제까지 반복할지 조건문을 설정한다

증감문 : 반복문을 수행하고 초기값을 늘리거나 줄이는 문장을 설정한다.

 

    for(let i = 0; i <= 10; i++){
                document.write(i + '<br>');
            }

 

 

 

 

 

while

초기문;
            while(조건문){
                //반복될 구문
                증감문;
            }
           
    let x = 0;
            while(x <= 10){
                document.write(x + '<br>');
                x += 2;
            }

 

 

 

 

do while (일단~ while안에 있는 조건문이 참이면 해라)

do{
                //반복될 구문
                증감문;
            } while(조건문);
    let y = 0;
            do{
                document.write(y+'<br>');
                y += 2;
            } while(y<=10);
           

 

 

 

 

 

forEach

대상은 무조건 배열로 있어야함.
            대상.forEach(function( 원소, 각원소 인덱스, 전체원소 ){
                //반복할 일
            });
           
let arr = ['a','b','c','d','e'];
            arr.forEach(function(item, index, all){
                document.write(item + '는 전체 배열' + all + '에서' + index + '번째 입니다 <br>');
            });

index번호를 활용할 수 있어서 좋음

 

 

 

 

 

for in → 객체에서만 사용가능!!

    for(각프로퍼티 변수 in 객체명){
                반복할 ;
            }

객체의 값에서 반복문 출력할때 사용한다.

객체 = 변수 + 함수

for(item in student){
                document.write(item + ':' + student[item] + '<br>');
            }

 

 

for of → 배열에서 사용할 수 있는 반복문

배열의 값 반복문

for( 원소변수 of 배열명){
                반복할
            }
let arr = ['a','b','c','d','e'];
       
            for(item of arr){
                document.write(item + '<br>')
            }