JAVASCRIPT 27 Literaion for loops

 자바스크립트의 반복문에 대해 알아보자!.

프로그램을 작성하다 보면 반복적인 코드를 써야 할 때가 있다. 물론 한땀 한땀 써도 코드는 잘 돌아 가곘지만 문제는 DRY (Don't repeat youself) 의 원칙에 어긋난다.

반복문인 for 문에 대해 알아보자. for 문도 if/else 문과 같은 controll data structure이다.

for (let rep = 1; rep <= 10; rep++) {
    console.log(`lift ${rep}`);}
 for ([initialization]; [condition]; [final-expression])

for문은 다음 세가지로 구분되며 먼저 

intialization 에서는 식 또는 변수 선언을 해줍니다. 식일 경우는 변수 초기화를 위해 사용한다.

condition 이 true 인 동안에만 for문이 작동합니다.

final - expression 은 매번 반복문을 실행시키고 마지막에 실행할 식입니다. 보통 카운터 변수를 증감하거나 바꿀 때 사용한다.

const years = [1231, 1890, 1493, 2001];
const ages = [];

for (let i = 0; i < years.length; i++) {
    ages.push(2020 - years[i]);
}

for 문과 array를 응용하면 간단한 문제가 많다.


반복문에서 사용하는 명령어로 continue 그리고 break 가 있다.

continue 는  현재 실행하고 있는 반복을 중단시키고 다음 반복으로 가서 실행시킨다.(skip)처럼 사용된다.

break 는 완전히 루프를 종료시킨다.

for (let i = 0; i < years.length; i++) {
    if (1231 === years[i]) continue;
    ages.push(2020 - years[i]);
}

추가된 줄에선 배열 years 에 1231 값이 나오면 skip 한다는 예시이다.


그리고 다른 반복문인 while loop에 대해 설명하겠다.

while 문은 

while (dice !== 6) {
    console.log(`you rolled a ${dice}`);
    dice = Math.trunc(Math.random() * 6) + 1;
    if (dice === 6) console.log('loops is end!');
}

for문 과 다르게 숫자를 세기 위한 counter 이 없다.

이는 얼마나 반복 될지 모르는 걸 계산 할 때 사용 하기 유리하다는 의미이다.

while 괄호 안의 값이 false 가 되면 loop를 종료 한다.

continue is to exit the current iteration of the loop and continue to next one

break is completely terminate the loop




































댓글

이 블로그의 인기 게시물

Javascript this keyward

Javascript Object vs Primitives (Primitives vs reference type)

javascript 15 switch statement