[JavaScript 기초] 3. 반복문 요약 정리

Hyun Jin·2022년 12월 19일
0

JavaScript

목록 보기
5/20
post-thumbnail

1. for문


구문 :
for ([initialization]; [condition]; [final-expression]) {statement}
for (초기값; 조건식; 증감식) {실행할 코드}

예시

for (let i = 1; i <= 3; i++) {
	console.log(i); // 1 2 3
}

1. 초기값(initialization): 증감식 반복횟수를 카운트하는 역할을 하는 변수. 주로 카운터 변수를 초기화할 때 사용함.
초기값은 반복문의 코드블록 내부에서만 유효함.(let 키워드로 선언한 변수는 반복문의 지역 변수가 됨)
식의 결과는 버려짐.

2. 조건식(condition): 매 반복마다 코드블록 내부의 코드를 실행 여부를 결정함. true -> 코드실행, false -> 반복문 종료.(for 문의 바로 다음 식으로 건너뜀)
조건식을 넣지 않을 경우 () 계산 결과는 언제나 참이 됨.

3. 증감식(final-expression): 코드블록 내부의 코드를 실행한 후 초기값으로 선언된 카운터 변수를 증가 또는 감소시키기 위한 표현식.

4. 실행할 코드(statement): 조건의 평가 결과가 참일 때 실행하는 문.
여러 문을 반복 실행하려면 블럭문({ ... }), 아무것도 실행하지 않으려면 공백문 (;)을 사용함.


2. 반복문 활용하기


1. 반복문 활용하기
if 조건문 안에 반복문 사용하기

2. 문자열과 반복문

  • 문자열의 속성 복습 :

    1. 인덱스(index)

    • 각 문자의 순서(인덱스) : str[0]
    • 특정 문자의 인덱스 확인 : indexOf('특정 문자)
      만약 찾는 문자가 2개 이상일 경우, 가장 앞에 있는 문자의 인덱스를 조회함.

    2. 길이(length)

    • 문자열의 길이 : str.length
    • 문자열의 마지막 문자의 인덱스는 문자열의 길이보다 1만큼 작음!(인덱스는 0부터 시작하고, 문자열은 해당 문자열 안의 문자의 총 숫자를 반환하니까)
      그래서 i = str.length 으로 조건식을 작성하면 마지막 인덱스+1 의 횟수까지 반복문이 실행됨.
      i <= str.length - 1(또는 i < str.length)로 조건식을 작성하면, 문자열의 끝까지 순회하는 반복문을 구현할 수 있음.

활용 예시 :

let str = 'christmas';
for (let i = 0; i <= str.length - 1; i++) {
	console.log(str[i]);
}

3. 반복문과 조건문


조건문을 활용하면 특정 조건에 따라 반복문이 실행되도록 작성 가능.

기타 알아둘 것

  • 공백도 하나의 문자열로 취급됨(index 로 조회되며, 문자열의 길이에 포함됨)
  • 짝수 조건문 : (i % 2 === 0)
  • 홀수 조건문 : (i % 2 ===1)

4. 반복문의 중첩


반복문 내부에 또 다른 반복문 사용 가능함.
반복문이 여러번 중첩되었을 경우
외부 반복문의 초기화와 조건식 평가가 true 면 내부 반복문의 초기화 조건식 평가가 실행되며,
내부 반복문 조건식의 조건식 평가가 falsy가 되면 내부 반복문이 종료되고
외부 반복문의 증감식과 조건식 평가가 이루어짐.

활용 예시 : 구구단 출력

for (let x = 2; x <= 9; x++) {
  for (let y = 1; y <= 9; y++) {
    console.log(`${x} x ${y} = ${x * y}`);
  }
}

5. while 문


while 문 : 조건문이 true일 때 실행되는 반복문.(조건문이 0이 되면 falsy 값이 되어 멈추게 됨!!)
조건식 평가(true || false)는 실행할 코드(statement)가 실행되기 전에 이루어진다.
iteration : 반복문 본문이 한 번 실행되는 것.
주의 : 무한루프(반복문이 종료되는 조건식이 항상 참이어서 무한히 반복되는 현상)

+) while (i != 0)을 짧게 줄여 while (i) 로 표현 가능!

let i = 3;
while (i) { // i가 0이 되면 조건이 falsy가 되므로 반복문이 멈춥니다.
  alert( i );
  i--;
}

* 반복문 빠져나오기 :
1. break : 반복문 종료.

Syntax
break;
break label;

  • A break statement, with or without a following label, cannot be used within the body of a function that is itself nested within the current loop, switch, or label statement that the break statement is intended to break out of.

2. continue :전체 반복문을 종료하지 않고, 현재 실행 중인 이터레이션을 멈추고 반복문이 다음 이터레이션을 강제로 실행시키도록 함.(조건을 통과할 때)

continue;
continue label;

  • The continue statement terminates execution of the statements in the current iteration of the current or labeled loop, and continues execution of the loop with the next iteration.
  • In contrast to the break statement, continue does not terminate the execution of the loop entirely, but instead:
    • In a while loop, it jumps back to the condition.
    • In a for loop, it jumps to the update expression.
  • ‘?’ 오른쪽엔 break나 continue가 올 수 없음. 표현식이 아닌 문법 구조(syntax construct)는 삼항 연산자 ?에 사용할 수 없음.

3. label : break 문을 사용하면 해당하는 여러 개의 중첩 반복문을 한번에 빠져나올 수 있음.

Syntax
label: statement(ex. for loop)

  • The labeled statement can be used with break or continue statements. It is prefixing a statement with an identifier which you can refer to.
  • break can be used with any labeled statement, and continue can be used with looping labeled statements.
  • You can use a label to identify a loop, and then use the break or continue statements to indicate whether a program should interrupt the loop or continue its execution.
  • Note that JavaScript has no goto statement; you can only use labels with break or continue.

do…while문
while 뒤에 오는 조건식이 true로 평가되는 동안 do 뒤에 오는 코드블록 내부의 코드를 반복해서 실행함.
do 의 코드블록 내부의 코드가 최소 한 번은 실행된 후에 조건식 평가가 실행됨.

구문

do
  statement
while (condition);

예제(MDN)

let result = '';
let i = 0;
do {
   i += 1;
   result += i + ' ';
}
while (i > 0 && i < 5);
// Despite i == 0 this will still loop as it starts off without the test
console.log(result);

-> do 내부에서 i 가 1 증가하므로 while 조건식이 실행되는 시점에는 i = 1 이 됨.
while 조건식의 결과는 true가 되고 반복문이 실행됨.

예제2(MDN article)

const cats = ['Bill', 'Jeff', 'Pete', 'Biggles', 'Jasmin'];
let myFavoriteCats = 'My cats are called ';
let i = 0;
do {
  if (i === cats.length - 1) {
    myFavoriteCats += `and ${cats[i]}.`;
  } else {
    myFavoriteCats += `${cats[i]}, `;
  }
  i++;
} while (i < cats.length);
console.log(myFavoriteCats);
  • +) for문과 while문을 주로 사용하는 상황
  1. for문을 사용하는 경우 :

    반복 횟수가 비교적 명확할 때
    배열, 문자열 내부를 순회할 때
    반복문의 중첩이 필요할 때

  2. while문을 사용하는 경우 :

    반복 횟수가 명확하지 않을 때

profile
새싹 프론트엔드 개발자

0개의 댓글