For-In 루프를 사용하여 배열 요소 반복
이 단계에서는 JavaScript 의 for-in 루프에 대해 배웁니다. for-in 루프는 객체의 속성 또는 배열의 요소를 반복하는 쉬운 방법을 제공합니다.
WebIDE 를 사용하여 ~/project 디렉토리에 forInLoop.js라는 새 파일을 만듭니다.
// for-in 루프를 사용하여 배열 반복
let fruits = ["apple", "banana", "cherry", "date"];
console.log("Iterating through Array Indices:");
for (let index in fruits) {
console.log(`Index: ${index}, Fruit: ${fruits[index]}`);
}
// for-in 루프를 사용하여 객체 반복
let student = {
name: "John Doe",
age: 22,
major: "Computer Science",
gpa: 3.8
};
console.log("\nIterating through Object Properties:");
for (let property in student) {
console.log(`${property}: ${student[property]}`);
}
// 실용적인 예: 항목의 총 가격 계산
let shoppingCart = [
{ name: "Laptop", price: 1000 },
{ name: "Headphones", price: 100 },
{ name: "Mouse", price: 50 }
];
console.log("\nCalculating Total Price:");
let totalPrice = 0;
for (let index in shoppingCart) {
totalPrice += shoppingCart[index].price;
}
console.log(`Total Price: $${totalPrice}`);
JavaScript 파일을 실행하여 for-in 루프가 작동하는 것을 확인합니다.
node ~/project/forInLoop.js
예시 출력:
Iterating through Array Indices:
Index: 0, Fruit: apple
Index: 1, Fruit: banana
Index: 2, Fruit: cherry
Index: 3, Fruit: date
Iterating through Object Properties:
name: John Doe
age: 22
major: Computer Science
gpa: 3.8
Calculating Total Price:
Total Price: $1150
for-in 루프에 대한 주요 사항:
- 배열과 객체 모두에서 작동합니다.
- 인덱스 (배열의 경우) 또는 속성 (객체의 경우) 을 반복합니다.
- 기존의 인덱스 기반 루프를 사용하지 않고 요소에 액세스하는 간단한 방법을 제공합니다.
- 배열과 함께 사용할 때는 주의하십시오. 모든 열거 가능한 속성을 반복합니다.
유연성을 보여주는 다른 예제를 살펴보겠습니다.
// for-in 루프를 사용하여 데이터 필터링 및 변환
let grades = {
math: 85,
science: 92,
english: 78,
history: 88
};
console.log("Filtering Grades Above 80:");
for (let subject in grades) {
if (grades[subject] > 80) {
console.log(`${subject}: ${grades[subject]}`);
}
}
파일을 다시 실행합니다.
node ~/project/forInLoop.js
예시 출력:
Filtering Grades Above 80:
math: 85
science: 92
history: 88