for...of와 for...in은 자바스크립트에서 반복(iteration)에 사용되지만, 사용 목적과 동작 방식이 다릅니다. 아래에서 그 차이를 자세히 살펴보겠습니다.
for...ofSet, Map 등의 요소를 직접 가져오는 데 사용됩니다.Set, Map 등과 같은 iterable 객체여야 합니다.for...of는 반복 가능한 객체의 iterator를 사용하여 요소를 하나씩 가져옵니다.=> for...of는 반복 횟수를 별도로 지정하지 않아도, 순회 가능한 객체의 모든 요소를 자동으로 처리하며, 자동 종료되기 때문에 사용이 간편합니다. 🙂
const arr = [1, 2, 3, 4, 5];
for (const num of arr) {
console.log(num); // 1, 2, 3, 4, 5 출력
}
const str = "hello";
for (const char of str) {
console.log(char); // h, e, l, l, o 출력
}
Set 순회const mySet = new Set([10, 20, 30]);
for (const value of mySet) {
console.log(value); // 10, 20, 30 출력
}
Map 순회const myMap = new Map([
["a", 1],
["b", 2],
["c", 3]
]);
for (const [key, value] of myMap) {
console.log(key, value); // a 1, b 2, c 3 출력
}
for...of에서 반복 횟수 조정break를 사용하면 됩니다.continue를 사용하세요.break)const arr = [1, 2, 3, 4, 5];
for (const num of arr) {
if (num === 3) break;
console.log(num); // 1, 2 출력
}
continue)for (const num of arr) {
if (num % 2 === 0) continue;
console.log(num); // 1, 3, 5 출력
}
Array)String)SetMapNodeList)arguments 객체for...infor...in 문도 별도로 반복 횟수를 지정하지 않아도 됩니다.
for...in은 반복 대상 객체의 열거 가능한(enumerable) 속성(키 또는 인덱스)을 자동으로 순회하며, 대상 객체의 속성이 모두 처리되면 반복을 종료합니다.
=> for...in은 반복 횟수를 명시하지 않아도 대상 객체의 열거 가능한 속성 키의 개수에 따라 자동으로 결정됩니다. 😊
const obj = { a: 1, b: 2, c: 3 };
for (const key in obj) {
console.log(key); // 출력: a, b, c
}
for...in은 객체 obj의 키인 "a", "b", "c"를 자동으로 반복합니다.const array = [10, 20, 30];
for (const index in array) {
console.log(index, array[index]);
// 출력: 0 10, 1 20, 2 30
}
for...in은 인덱스(index)를 순회합니다.for...in에서 반복 횟수 조정break: 반복을 중단하고, for...in 루프를 즉시 종료합니다. continue: 현재 반복을 건너뛰고, 다음 반복으로 넘어갑니다. break 사용const obj = { a: 1, b: 2, c: 3 };
for (const key in obj) {
if (key === 'b') break; // 'b'를 만나면 루프 종료
console.log(key, obj[key]);
// 출력: a 1
}
continue 사용const obj = { a: 1, b: 2, c: 3 };
for (const key in obj) {
if (key === 'b') continue; // 'b'를 건너뛰고 다음 반복으로 넘어감
console.log(key, obj[key]);
// 출력: a 1
// 출력: c 3
}
for...in이 배열의 인덱스를 순회할 때도 break와 continue를 사용할 수 있습니다.
breakconst arr = [10, 20, 30];
for (const index in arr) {
if (index == 1) break; // 인덱스 1에서 종료
console.log(index, arr[index]);
// 출력: 0 10
}
continueconst arr = [10, 20, 30];
for (const index in arr) {
if (index == 1) continue; // 인덱스 1을 건너뛰기
console.log(index, arr[index]);
// 출력: 0 10
// 출력: 2 30
}
const obj = { a: 1, b: 2, c: 3 };
// for...in으로 객체 순회
for (const key in obj) {
console.log(key, obj[key]);
// 출력: a 1, b 2, c 3
}
const array = [10, 20, 30];
// for...in으로 배열 순회
for (const index in array) {
console.log(index, array[index]);
// 출력: 0 10, 1 20, 2 30
}
for...of와 for...in 비교| 특성 | for...of | for...in |
|---|---|---|
| 반환 값 | 값 (배열의 요소, 문자열의 문자 등) | 키 (객체의 속성, 배열의 인덱스) |
| 대상 | 반복 가능한 객체 (iterable) | 열거 가능한 객체 (enumerable) |
| 주요 사용 대상 | 배열, 문자열, Set, Map 등 | 객체 속성 순회 |
| 사용 목적 | 요소를 직접 가져오는 작업 | 키/인덱스를 순회하는 작업 |
| 순회 속성 | 배열, 문자열 등에서 적합 | 객체 속성 순회에 적합 |
for...in 사용 시 상속된 속성 포함 가능:
hasOwnProperty로 필터링하세요.const obj = { a: 1 };
Object.prototype.b = 2;
for (const key in obj) {
if (obj.hasOwnProperty(key)) {
console.log(key); // 출력: a
}
}
배열에 for...in 사용 시 주의:
for...in은 인덱스를 반환하므로, 배열을 순회하는 데는 권장되지 않습니다.for...of나 forEach를 사용하는 것이 더 적합합니다.const array = [10, 20, 30];
array.customProperty = "hello";
for (const index in array) {
console.log(index, array[index]);
// 출력: 0 10, 1 20, 2 30, customProperty hello
}
객체에 for...of 사용 불가:
for...of를 직접 사용할 수 없습니다.Object.keys, Object.values, 또는 Object.entries와 함께 사용하세요.const obj = { a: 1, b: 2, c: 3 };
for (const key of Object.keys(obj)) {
console.log(key, obj[key]);
// 출력: a 1, b 2, c 3
}
for...of: 값을 가져오고 싶을 때 사용 (배열, 문자열, Set, Map 등).for...in: 객체의 속성 키나 배열의 인덱스를 가져올 때 사용.배열 순회에는 for...of를, 객체 속성 순회에는 for...in을 사용하는 것이 적합합니다! 😊