JS 반복문

shinyeongwoon·2022년 10월 25일
0

JS

목록 보기
8/16

while 문

  • 무한 loop
while(true){
	console.log('hi');
}
let i = 1;
while(i <= 100){
  console.log('hi');
  i++;
}

for문

for(let i = 0 ; i < 100 ; i++){
	console.log('hi');
}

for문의 다양한 형태

for in 문 (객체의 프로퍼티 키 열거 전용)

객체의 열거 속성을 통해 지정된 변수를 반복한다.
즉, 객체에 접근해서 객체의 값들을 for in문으로 활용할 수 있다.

const obj = {
	a:1,
    b:2,
    c:3,
};

for (let i in obj){
	console.log(i,obj[i]);
}

for of문 (이터러블 순회 전용)

반복 가능한 객체 (배열, 문자열 , Map 등)를 통해 반복문을 만든다. for in문에 비해 성능이 좋다.

const str = 'hello';
for (let s of str){
	console.log(s);
}

forEach문 (배열 순회 전용 메소드)

주어진 함수를 배열 요소 각가에 대해 실행하게 된다.

배열.forEach(function(value,index,array){
	반복수행코드;
});

//ex)
const myArr = [1,2,3,4,5];
const newMyArr = myArr.forEach((value,index,array) => {
	console.log(`요소 : ${value}`);
    console.log(`index : ${index}`);
    console.log(array);
});
console.log(newMyArr);

결과 )
요소 : 1
index : 0
[1,2,3,4,5]

요소 : 2
index : 1
[1,2,3,4,5]

요소 : 3
index : 2
[1,2,3,4,5]

요소 : 4
index : 3
[1,2,3,4,5]

요소 : 5
index : 4
[1,2,3,4,5]

undefined

break 문으로 반복문 멈추기

let i = 0;
while(true){
	if(i === 5) break;
  	i++;
}
console.log(i);

결과 )
5

continue 문으로 코드 실행 건너뛰기

let i = 0;
while(i<10){
	i++;
  	if(i % 2 === 0){
    	continue;
    }
	console.log(i);
}

0개의 댓글