개발일기

항상 까먹는 for of, for in 간단하게 기록 해 두기 본문

TIL

항상 까먹는 for of, for in 간단하게 기록 해 두기

황대성 2024. 3. 30. 20:17

1. for of

배열의 요소를 반복한다.

array = ["apple","banana",'orange']

for (const iterator of array) {
    console.log(iterator)
}
//Expected output : 
//apple
//banana
//orange

 

2. for in

배열의 인덱스를 반복한다.

array = ["apple","banana",'orange']

for (const key of array) {
    console.log(key)
}
//Expected output : 
//0
//1
//2

 

3. for of, for in 객체 실행해 보기

object = {name:"Jhon", age:21, city : 'Busan'}

for (const iterator of object) {
    console.log(iterator)
}
//Expected output : TypeError: object is not iterable

 

for of에서 객체 실행시 타입 에러와 함께 반복 불가능 하다는 에러가 나온다. 

 

object = {name:"Jhon", age:21, city : 'Busan'}

for (const key in object) {
    console.log(key)
}
//Expected output : 
//name
//age
//city

 

for in문 에서 객체 실행시 객체의 value값이 아닌 key값을 반복해서 출력해 주는 것을 볼 수 있다.

만약 객체의 value값에 접근하고 싶다면 아래와 같이 접근해야 할 것 같다.

console.log(object[key])