for문의 종류와 사용 방법을 간단하게 정리해본다.
for 문for (초기식; 조건식; 증감식) {
// 반복 실행될 코드 블록
}
예제 코드
for (let i = 1; i <= 5; i++) {
console.log(i); // 1, 2, 3, 4, 5
}
💡 Reference : https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Statements/for
for...in 문for (변수 in 객체) {
// 객체의 각 속성에 대해 실행될 코드 블록
}
예제 코드
const person = {
name: 'John',
age: 30,
city: 'New York'
};
for (let key in person) {
console.log(key + ': ' + person[key]);
}
// 출력 결과:
// name: John
// age: 30
// city: New York
💡 Reference : https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Statements/for...in
for...of 문for (변수 of 배열 또는 이터러블 객체) {
// 각 요소에 대해 실행될 코드 블록
}
예제 코드
const fruits = ['apple', 'banana', 'orange'];
for (let fruit of fruits) {
console.log(fruit);
}
// 출력 결과:
// apple
// banana
// orange
💡 Reference : https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Statements/for...of
for...each 문배열.forEach(function(요소, 인덱스, 배열) {
// 각 요소에 대해 실행될 코드 블록
});
예제 코드
const numbers = [1, 2, 3, 4, 5];
numbers.forEach(function(number) {
console.log(number * 2);
});
// 출력 결과:
// 2
// 4
// 6
// 8
// 10
💡 Reference : https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach
for...await...of 문Promise나 async 함수를 포함하는 비동기 작업을 처리할 때 유용하다.for await...of 문은 async 함수나 Promise를 반환하는 함수 안에서만 사용할 수 있다는 것에 주의한다.for await (변수 of 비동기 이터러블 객체) {
// 각 요소에 대해 비동기적으로 실행될 코드 블록
}
예제 코드
// 비동기 함수 정의
async function asyncFunction(item) {
return new Promise(resolve => {
setTimeout(() => {
resolve(item);
}, 1000);
});
}
// 비동기 이터러블 객체
const asyncIterable = {
[Symbol.asyncIterator]: async function* () {
yield await asyncFunction('첫 번째');
yield await asyncFunction('두 번째');
yield await asyncFunction('세 번째');
}
};
// for...await...of 문을 사용하여 비동기적으로 각 요소 실행
(async () => {
for await (const item of asyncIterable) {
console.log(item);
}
})();
/* 실행 결과:
1초 후: "첫 번째"
2초 후: "두 번째"
3초 후: "세 번째"
*/
💡 Reference : https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Statements/for-await...of