구문반복 대상반복되는 값사용 예
for...in | 객체의 key | key (문자열) | 객체 |
for...of | 이터러블(iterable) (배열, 문자열 등) | 실제 요소 값 | 배열, 문자열, Set, Map 등 |
1. for...in – 객체의 key를 반복
const user = { name: "Tom", age: 30 };
for (const key in user) {
console.log(key); // "name", "age"
console.log(user[key]); // "Tom", 30
}
- 객체의 속성 이름(key) 에 접근함
- 배열에도 사용 가능하지만 index(숫자 문자열) 를 반환해서 추천하지 않음
const arr = ['a', 'b', 'c'];
for (const i in arr) {
console.log(i); // "0", "1", "2"
console.log(arr[i]); // "a", "b", "c"
}
⚠️ 배열엔 아래의 for...of가 더 적합. <-------------------
2. for...of – 이터러블의 값을 반복
const arr = ['a', 'b', 'c'];
for (const value of arr) {
console.log(value); // "a", "b", "c"
}
- 배열, 문자열, Set, Map 같은 이터러블에 사용
- 배열의 값 그 자체를 반복함
const text = "hello";
for (const char of text) {
console.log(char); // "h", "e", "l", "l", "o"
}