개발일기
항상 까먹는 for of, for in 간단하게 기록 해 두기 본문
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])
'TIL' 카테고리의 다른 글
NextJs 페이지 라우팅 및 동적 라우팅(TodoList 만들기) (0) | 2024.04.20 |
---|---|
cannot read properties of undefined (reading 'protocol') (0) | 2024.04.15 |
next.js 시작하기 (yarn 사용) (0) | 2024.03.27 |
CSR vs SSR (0) | 2024.03.25 |
useEffect 알아보기 (0) | 2024.03.11 |