본문 바로가기

JS - 반복문 심화1 (break / continue / for in / for of / forEach / while) 본문

개발/JavaScript

JS - 반복문 심화1 (break / continue / for in / for of / forEach / while)

자전하는명왕성 2023. 1. 12. 12:03

break : 원하는 구간에서 반복문 종료

// break 예시

for(let i = 0 ; i < 5 ; i++){
  if(i===2){
    break 			// break의 경우 switch 반복문에서 항상 사용
  }
  console.log(i) 	// 0 1
}

 

continue : 해당 구간의 반복문을 실행하지 않음 (생략)

// continue 예시

for(let i = 0 ; i < 5 ; i++){
  if(i===2){
    continue
  }
  console.log(i)   // 0 1 3 4 
}

 

반복문의 여러 문법

 

for ~ in

// Key ~ in 예시

const obj = {
  name : 'otter',
  age : 30
}
for(let key in obj){
  console.log(key, obj[key]) 	// 'name' 'otter' / 'age' 30 출력
}
// 이때 꼭 key 로 정의될 필요 없음
// Key ~ in 예시 2

const str = 'abcde'

for(let data in str){
  console.log(data)
}

 

for ~ of

// for ~ of 예시

const arr = ['a','b','c']
for(let data of arr){
  console.log(data)	 	// 'a' , 'b', 'c' 출력
}

 

forEach (엄밀히 말하면 반복문보다는 메서드에 가까움 / 배열에만 사용 가능)

// forEach 예시

const arr = ['a','b','c']

arr.forEach((data,idx, array) => {
  console.log(data,idx, array)
})

// 'a' 0 [ 'a', 'b', 'c' ]
// 'b' 1 [ 'a', 'b', 'c' ]
// 'c' 2 [ 'a', 'b', 'c' ]
// value, index, array 까지 반환 가능

콜백 함수 : 함수에 인자로 전달되는 함수를 말한다.

forEach 메서드의 경우 break, continue 사용이 불가하다.

 

while

// 최초식
let answer = 0 // 로봇의 움직인 횟수
let current = 1 // 로봇의 현재 위치

// 조건식
while(current !== 100){
  // 증감문
  current++;
  answer++;
}
answer		// 99

while 문의 경우, 언제 반복문을 종료해야 할지 알 수 없거나 정해지지 않았을 때 사용한다.

단, 조건식이 정해지지 않으면 무한하게 연산하기 때문에, '조건식'을 정해줄 필요가 있다.

 

 

Comments