2.13 Loops: while and for

히진로그·2022년 2월 2일
0

Modern-Javascript

목록 보기
10/14

출처: https://javascript.info/

  • 혼자 읽고 타이핑하며 이해하면서 공부한 흔적 남기기

Loops are a way to repeat the same code multiple times.

The "while" loop

while(condition) {
	// code
	// so-called "loop body"
}

While the condition is truthy, the code from the loop body is executed.

let i = 0;

while(i<3) {
    alert(i);
    i++;
}

A single execution of the loop body is called an iteration.

loop body의 single execution을 iteration이라고 부른다.

The "do..while" loop

do {
	// loop body
} while(condition);

The loop will first execute the body, then check the condition, and, while it's truthy, execute it again and again.

body를 먼저 실행한 후 조건을 체크한다. 조건이 true일 경우 body를 계속 실행한다.

이 구문은 조건에 상관없이 루프를 한 번 이상 실행시킬때 사용해야한다.

The "for" loop

자주 사용되는 루프이다.

for(begin; condition; step) {
	// ... loop body ...
}
for(let i = 0; i < 3; i++) {
	alert(i);
}

Untitled

The general loop algorithm works like this.

Run begin
→ (if condition → run body and run step)
→ (if condition → run body and run step)
→ (if condition → run body and run step)
→ ...

That is, begin executes once, and then it iterates: after each condition test, body and step are executed.

begin이 한번 실행되면, 그 다음 iterates된다.

조건 실행 후 본문과 다음 스텝이 실행된다.

Skipping parts

Any part of for can be skipped.

We can actually remove everything, creating an infinite loop

for(;;) {
	// repeats without limits
}

two for semicolons ; must be present. Otherwise, there would be a syntax error.

Breaking the loop

보통 루프는 조건이 flasy이면 루프에서 빠져나온다.

But we can force the exit at any time using the special break directive.

The combination "infinite loop + break as needed" is great for situations when a loop's condition must be checked not in the beginning or end of the loop, but in the middle or even in several places of its body.

continue to the next iteration

The continue directive is a "lighter version" of break.

It doesn't stop the whole loop. Instead, it stops the current iteration and forces the loop to start a new one (if the condition allows).

전체 루프를 중단시키는 대신 현재 반복문을 중단시키고 루프의 처음으로 돌아가 새로운 반복을 시작한다. (조건이 허락하는 경우)

현재 반복문을 중단하고 다음으로 넘어가고 싶을 때 사용한다.

The continue directive helps decrease nesting

for (let i = 0; i < 10; i++) {

  if (i % 2) {
    alert( i );
  }

}

짝수는 나머지가 0이고 0은 if문에서 false로 변환되니까 alert가 실행이 안됨.

No break/continue to the right side of '?'

문법 구조syntax constructs는 ternary operator와 함께 쓰일 수 없다.

특히 break/continue 같은 지시자는 사용하면 안된다.

Labels for break/continue

Sometimes we need to break out from multiple nested loops at once.

가끔 여러개 중첩문을 한 번에 빠져나와야할 때도 있다.

A label is an identifier with a colon before a loop

label은 루프 앞에 콜론과 함께 쓰이는 식별자이다.

반복문 안에서 break 문을 사용하면 레이블에 해당하는 반복문을 빠져나올 수 있다.

continue 지시자를 레이블과 함께 사용하는 것도 가능하다. 두 가지를 같이 사용하면 레이블이 붙은 반복문의 다음 이터레이션이 실행된다.

0개의 댓글