JavaScript 루프 구조 탐구

JavaScriptBeginner
지금 연습하기

소개

이 랩에서는 학생들이 JavaScript 루프 구조를 깊이 있게 탐구하며 프로그래밍 논리의 기본이 되는 다양한 반복 기법을 살펴봅니다. 이 랩은 while 루프, do-while 루프, for 루프, for-in 루프를 포함한 필수 루프 유형을 다루며, 실용적인 코딩 예제와 점진적인 학습을 통해 각 구조에 대한 실질적인 경험을 제공합니다.

참가자들은 while 루프의 기본 구문을 이해하는 것부터 시작하여 제어된 반복을 생성하고 카운팅 및 조건부 검색과 같은 작업을 수행하는 방법을 배웁니다. 진행하면서 다양한 루프 구조를 구현하는 연습을 하고, 고유한 특성과 사용 사례를 비교하여 루프를 사용하여 데이터를 조작하고, 배열을 반복하며, JavaScript 에서 동적 프로그래밍 솔루션을 만드는 방법에 대한 포괄적인 이해를 개발하는 데 도움이 됩니다.

while 루프 구문 및 기본 사용법 이해

이 단계에서는 JavaScript 에서 while 루프의 기본 구문과 사용법에 대해 배웁니다. While 루프는 지정된 조건이 참인 동안 코드 블록을 반복할 수 있게 해주는 기본적인 제어 구조입니다.

while 루프를 탐색하기 위해 새로운 JavaScript 파일을 만들어 보겠습니다. WebIDE 를 열고 ~/project 디렉토리에 whileLoop.js라는 파일을 만듭니다.

// 1 부터 5 까지 세는 간단한 while 루프 생성
let count = 1;

while (count <= 5) {
  console.log(`Current count: ${count}`);
  count++;
}

이제 Node.js 를 사용하여 JavaScript 파일을 실행하여 출력을 확인합니다.

node ~/project/whileLoop.js

예시 출력:

Current count: 1
Current count: 2
Current count: 3
Current count: 4
Current count: 5

while 루프 구문을 자세히 살펴보겠습니다.

  • let count = 1;은 루프 전에 카운터 변수를 초기화합니다.
  • while (count <= 5)는 루프를 계속하기 위해 참이어야 하는 조건을 정의합니다.
  • console.log()count의 현재 값을 출력합니다.
  • count++는 각 반복에서 카운터를 증가시킵니다.

이제 더 복잡한 조건을 가진 while 루프를 보여주는 더 실용적인 예제를 만들어 보겠습니다.

// 3 과 5 로 모두 나누어 떨어지는 첫 번째 숫자를 찾는 while 루프 생성
let number = 1;

while (!(number % 3 === 0 && number % 5 === 0)) {
  number++;
}

console.log(`First number divisible by 3 and 5: ${number}`);

파일을 다시 실행합니다.

node ~/project/whileLoop.js

예시 출력:

First number divisible by 3 and 5: 15

이 예제는 while 루프를 사용하여 특정 조건을 검색하거나 반복적인 작업을 수행하는 방법을 보여줍니다.

증가 반복을 사용한 do-while 루프 연습

이 단계에서는 JavaScript 의 do-while 루프에 대해 배웁니다. do-while 루프는 while 루프와 유사하지만 중요한 차이점이 있습니다. 즉, 조건 확인 전에 코드 블록이 최소 한 번 실행됩니다.

WebIDE 를 사용하여 ~/project 디렉토리에 doWhileLoop.js라는 새 파일을 만듭니다.

// 사용자 입력 시뮬레이션을 사용한 do-while 루프 시연
let attempts = 0;
let secretNumber = 7;
let guess;

do {
  // 1 과 10 사이의 임의의 추측 시뮬레이션
  guess = Math.floor(Math.random() * 10) + 1;
  attempts++;

  console.log(`Attempt ${attempts}: Guessed ${guess}`);

  if (guess === secretNumber) {
    console.log(
      `Congratulations! You guessed the number in ${attempts} attempts.`
    );
  }
} while (guess !== secretNumber);

JavaScript 파일을 실행하여 do-while 루프가 어떻게 작동하는지 확인합니다.

node ~/project/doWhileLoop.js

예시 출력:

Attempt 1: Guessed 3
Attempt 2: Guessed 9
Attempt 3: Guessed 7
Congratulations! You guessed the number in 3 attempts.

do-while 루프의 주요 특징:

  • 조건 확인 전에 코드 블록이 최소 한 번 실행됩니다.
  • 조건은 각 반복의 끝에서 확인됩니다.
  • 코드가 최소 한 번 실행되도록 하려는 경우 유용합니다.

do-while 루프를 더 자세히 설명하기 위해 다른 예제를 만들어 보겠습니다.

// do-while 루프를 사용한 점진적 반복 시연
let total = 0;
let i = 1;

do {
  total += i;
  console.log(`Current total: ${total}, Current number: ${i}`);
  i++;
} while (total < 10);

console.log(`Final total: ${total}`);

파일을 다시 실행합니다.

node ~/project/doWhileLoop.js

예시 출력:

Current total: 1, Current number: 1
Current total: 3, Current number: 2
Current total: 6, Current number: 3
Current total: 10, Current number: 4
Final total: 10

이 예제는 do-while 루프를 점진적 반복에 사용하여 종료 조건을 확인하기 전에 코드 블록이 최소 한 번 실행되도록 하는 방법을 보여줍니다.

제어된 반복을 위한 For 루프 구현

이 단계에서는 JavaScript 의 for 루프에 대해 배웁니다. for 루프는 명확한 시작, 끝 및 증가/감소 메커니즘을 통해 제어된 반복을 수행하는 간결한 방법을 제공합니다.

WebIDE 를 사용하여 ~/project 디렉토리에 forLoop.js라는 새 파일을 만듭니다.

// 1 부터 5 까지 숫자를 출력하는 기본 for 루프
console.log("Basic Counting Loop:");
for (let i = 1; i <= 5; i++) {
  console.log(`Current number: ${i}`);
}

// 숫자의 팩토리얼을 계산하는 for 루프
console.log("\nFactorial Calculation:");
let number = 5;
let factorial = 1;

for (let j = 1; j <= number; j++) {
  factorial *= j;
}

console.log(`Factorial of ${number} is: ${factorial}`);

// 배열을 반복하는 for 루프
console.log("\nArray Iteration:");
let fruits = ["apple", "banana", "cherry", "date"];

for (let k = 0; k < fruits.length; k++) {
  console.log(`Fruit at index ${k}: ${fruits[k]}`);
}

JavaScript 파일을 실행하여 다양한 for 루프 예제를 확인합니다.

node ~/project/forLoop.js

예시 출력:

Basic Counting Loop:
Current number: 1
Current number: 2
Current number: 3
Current number: 4
Current number: 5

Factorial Calculation:
Factorial of 5 is: 120

Array Iteration:
Fruit at index 0: apple
Fruit at index 1: banana
Fruit at index 2: cherry
Fruit at index 3: date

for 루프 구문을 자세히 살펴보겠습니다.

  • for (initialization; condition; increment/decrement)는 표준 구조입니다.
  • let i = 1은 루프 카운터를 초기화합니다.
  • i <= 5는 계속 조건을 정의합니다.
  • i++는 각 반복 후 카운터를 증가시킵니다.

더 복잡한 for 루프 사용법을 보여주는 다른 예제를 만들어 보겠습니다.

// 곱셈표를 만들기 위한 중첩 for 루프
console.log("Multiplication Table:");
for (let row = 1; row <= 5; row++) {
  let rowOutput = "";
  for (let col = 1; col <= 5; col++) {
    rowOutput += `${row * col}\t`;
  }
  console.log(rowOutput);
}

파일을 다시 실행합니다.

node ~/project/forLoop.js

예시 출력:

Multiplication Table:
1 2 3 4 5
2 4 6 8 10
3 6 9 12 15
4 8 12 16 20
5 10 15 20 25

이 예제는 중첩 for 루프를 사용하여 더 복잡한 반복 패턴을 만드는 방법을 보여줍니다.

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

다양한 루프 구조 비교 및 대조

이 단계에서는 JavaScript 의 다양한 루프 구조의 차이점을 살펴보고 각 루프 유형을 효과적으로 사용하는 시기를 배웁니다.

WebIDE 를 사용하여 ~/project 디렉토리에 loopComparison.js라는 새 파일을 만듭니다.

// 동일한 작업에 대한 다양한 루프 구조 시연

// 1. While 루프: 반복 횟수를 알 수 없을 때 가장 적합
console.log("While Loop Example:");
let whileCounter = 1;
while (whileCounter <= 5) {
  console.log(`While Loop: ${whileCounter}`);
  whileCounter++;
}

// 2. Do-While 루프: 최소 한 번 실행 보장
console.log("\nDo-While Loop Example:");
let doWhileCounter = 1;
do {
  console.log(`Do-While Loop: ${doWhileCounter}`);
  doWhileCounter++;
} while (doWhileCounter <= 5);

// 3. For 루프: 반복 횟수를 알 때 가장 적합
console.log("\nFor Loop Example:");
for (let forCounter = 1; forCounter <= 5; forCounter++) {
  console.log(`For Loop: ${forCounter}`);
}

// 4. For-In 루프: 객체 속성 반복
console.log("\nFor-In Loop Example:");
let student = {
  name: "John Doe",
  age: 22,
  major: "Computer Science"
};

for (let property in student) {
  console.log(`${property}: ${student[property]}`);
}

// 5. 루프 성능 비교
console.log("\nLoop Performance Comparison:");
const iterations = 1000000;

console.time("While Loop");
let a = 0;
while (a < iterations) {
  a++;
}
console.timeEnd("While Loop");

console.time("For Loop");
for (let b = 0; b < iterations; b++) {}
console.timeEnd("For Loop");

JavaScript 파일을 실행하여 비교를 확인합니다.

node ~/project/loopComparison.js

예시 출력:

While Loop Example:
While Loop: 1
While Loop: 2
While Loop: 3
While Loop: 4
While Loop: 5

Do-While Loop Example:
Do-While Loop: 1
Do-While Loop: 2
Do-While Loop: 3
Do-While Loop: 4
Do-While Loop: 5

For Loop Example:
For Loop: 1
For Loop: 2
For Loop: 3
For Loop: 4
For Loop: 5

For-In Loop Example:
name: John Doe
age: 22
major: Computer Science

Loop Performance Comparison:
While Loop: 2.345ms
For Loop: 1.876ms

주요 차이점:

  1. While 루프:

    • 반복 횟수를 알 수 없을 때 사용합니다.
    • 각 반복 전에 조건을 확인합니다.
    • 초기 조건이 false 이면 실행되지 않을 수 있습니다.
  2. Do-While 루프:

    • 최소 한 번의 실행을 보장합니다.
    • 각 반복 후에 조건을 확인합니다.
    • 코드를 최소 한 번 실행하려는 경우 유용합니다.
  3. For 루프:

    • 반복 횟수를 알 때 가장 적합합니다.
    • 초기화, 조건 및 증가를 포함하는 간결한 구문입니다.
    • 배열 반복 및 계산에 가장 일반적으로 사용됩니다.
  4. For-In 루프:

    • 객체 속성을 반복하기 위한 것입니다.
    • 객체와 배열 모두에서 작동합니다.
    • 인덱스 또는 속성 이름을 제공합니다.

올바른 루프를 선택하는 것을 보여주는 마지막 예제를 만들어 보겠습니다.

// 다양한 시나리오에 맞는 올바른 루프 선택
let numbers = [10, 20, 30, 40, 50];

// 조건부 검색을 위한 While 루프
console.log("\nChoosing the Right Loop:");
let searchValue = 30;
let index = 0;
while (index < numbers.length && numbers[index] !== searchValue) {
  index++;
}
console.log(`Found ${searchValue} at index: ${index}`);

// 간단한 반복을 위한 For 루프
console.log("Squared Numbers:");
for (let i = 0; i < numbers.length; i++) {
  console.log(`${numbers[i]} squared: ${numbers[i] * numbers[i]}`);
}

파일을 다시 실행합니다.

node ~/project/loopComparison.js

예시 출력:

Choosing the Right Loop:
Found 30 at index: 2
Squared Numbers:
10 squared: 100
20 squared: 400
30 squared: 900
40 squared: 1600
50 squared: 2500

요약

이 랩에서는 참가자들이 JavaScript 의 다양한 루프 구조를 탐구하여, 다양한 유형의 루프를 이해하고 구현하는 데 중점을 두었습니다. 랩은 while 루프에 대한 포괄적인 검토로 시작하여, 반복 횟수를 계산하고 특정 숫자 조건을 검색하는 예제를 통해 기본 구문과 실용적인 응용 프로그램을 시연했습니다. 참가자들은 루프 변수를 초기화하고, 루프 조건을 정의하며, 증가 연산자를 사용하여 루프 실행을 제어하는 방법을 배웠습니다.

랩은 do-while 루프, for 루프, for-in 루프를 포함한 추가 루프 유형을 다루면서 각 구조에 대한 실습 경험을 제공했습니다. 이러한 루프 메커니즘을 비교하고 대조함으로써 학습자들은 다양한 프로그래밍 시나리오에 적합한 루프 구조를 선택하는 방법에 대한 통찰력을 얻어 JavaScript 프로그래밍 기술과 제어 흐름 메커니즘에 대한 이해를 향상시켰습니다.