반복문 (for of, for in)

GoGoDev·2021년 12월 20일
0

JS & TS

목록 보기
2/11

For of 반복문

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

for(const item of arr) {
	console.log(item); // 'a' 'b' 'c' 'd'
}

배열을 순회할 때, 처음부터 끝까지 한번씩 읽으면서 순회할 때, 배열의 특정 위치를 필요로 하지 않을 때 쓰기 편하다

For in 반복문

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

for(const index in arr) {
	console.log(arr[index]); // 'a' 'b' 'c' 'd'
}

배열 arr에 있는 키 값(위치 값)을 넘겨준다.
in 오른쪽이 배열 or 객체 등 일 때, 그 키 값을 하나씩 꺼내욜 때 많이 사용한다.

const obj = {
	color: 'red,
    width: 200,
    height: 200,
}

for(const key in obj) {
	console.log(key) // 'color' 'width' 'height'
}

key의 이름만 빼와서 데이터를 다룰 때, 사용하기 용이하다.

profile
🐣차근차근 무럭무럭🐣

0개의 댓글